treeset 实现排序 实现comparable接口。
HashMap:
Java8前:数组+链表
通过hash(key.hashcode())%len计算要添加的元素存放的数组位置。
如果总是分配到同一个桶中,则会性能恶化从O(1)变成O(n)
Java8后:数组+链表+红黑树
TREEIFY_THRESHOLD 将链表转化成红黑树 将最坏性能从O(n)提升为O(logn)
HashMap put方法逻辑:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- 若HashMap未被初始化,则进行初始化操作
- 对Key求Hash值,依据Hash值计算下标
- 若未发生碰撞,则直接放入桶中
- 若发生碰撞,则以链表的方式链接到后面
- 若链表的长度超过阀值,且HashMap元素超过最低树化容量,则将链表转成红黑树
- 若链表的长度超过阀值,且HashMap元素没有超过最低树化容量,则直接进行resize
- 若节点已经存在,则用新值替换旧值
- 若桶满了(默认16*扩容因子0.75),就需要resize(扩容2倍重排)
get方法逻辑
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
- 通过key求hash值,依据hash值找到桶的位置
- 通过key.equals方法找到相应值 返回
如何减少碰撞:
- 扰动函数
- 使用final对象,并采用合适的equals 和 hashcode方法;final不可变性能够缓存不同键的hashcode,使用String,Integer为key很适合。
扩容问题:
- 多线程环境,存在条件竞争
- rehashing是一个耗时过程
使hashmap线程安全方法:
Map hashMap = new HashMap<>();
Map safeHashMap = Collections.synchronizedMap(hashMap);
synchronizedMap ,public方法使用mutex对象锁,再多线程环境下串行执行,效率低。
HashTable
- 线程安全:涉及到修改HashTable的方法,使用Synchronized修饰
- 串行化方式运行,性能较差
- 与hashmap类似
ConccurentHashMap
早期使用分段锁 Segment实现。将hashmap一个数组拆分多个数组并分别加锁。
java8:CAS+synchronized 使锁细化。
首先采用无锁操作CAS插入头节点,如果操作失败说明已经有其他线程插入头节点
则循环重试。
casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null))
若头节点已经存在,则尝试通过synchronized获取头节点的同步锁,在进行操作
CAS
CAS(Compare and Swap)乐观锁。只在提交操作时候检查是否违反数据完整性,提交失败则重试。
一种高效实现线程安全性的方法。CAS操作失败时由开发者决定是继续尝试,还是执行其他操作。
操作思想:
包含三个操作数:内存位置(V-主内存值)/预期原值(A)/新值(B)
当V与A相匹配,则V更新为B,否则处理器不做任何操作。
put方法:
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
-
判断Node数组是否初始化,没有则进行初始化
-
通过hash定位数组索引坐标,是否有Node节点,如果没有则使用通过CAS进行添加(链表头节点),添加失败则进入下一次循环。
-
检查到内部正在扩容,就帮助它一块扩容(helpTransfer(tab, f);)
-
否则使用synchronized锁住f元素(链表/红黑二叉树的头元素)
如果是链表结构,则执行链表添加操作
如果是树型结构,则执行树添加操作 -
判断链表长度已经达到临界点8(默认值TREEIFY_THRESHOLD)时,将链表转化为树结构 (treeifyBin(tab, i);)
注意:
size() 和 mappingCounting 方法区别,两者计算是否准确?
多线程环境下如何控制扩容?
HashMap/HashTable/ConccurentHashMap区别:
- hashmap线程不安全:数组+链表+红黑树
- hashtable线程安全:数组+链表。通过锁住整个hashtable来实现线程安全。效率低、
- ConccurentHashMap线程安全:数组+链表+红黑树。通过CAS+synchronized将锁细粒度到数组的每个元素来提升并发性能
- HashMap key 和value均可以为null。hashtable和concurrenthashmap不支持。