HashMap扩容
table数组初始长度默认16,如果自定义长度不是2的次方,会转换为满足2的次方的最小的且大于自定义值的长度,默认负载因子0.75,如果table数组实际存覆盖率超过0.75,会扩容为2倍。
链表长度阈值默认8,如果链表长度超过8,会先判断table数组长度,如果table数组长度超过64,则会将链表转换为红黑树,否则会先将table数组扩容。 当删除元素使红黑树节点数目降至6时,红黑树会转回链表。
ConcurrentHashMap锁
ConcurrentHashMap是线程安全的,在用put方法添加键值对时,当要修改的table数组对应的Node节点还是空时,即没有哈希冲突时,使用CAS乐观锁来修改当前Node节点,其中调用了Unsafe包中的compareAndSwapObject方法,该方法是native方法,由c++实现,即期待值为空,修改后的值为新的Node节点,当前实际值根据传入的table数组对象和偏移量(哈希值)在compareAndSwapObjectCAS中查得。
当要修改的table数组对应的Node节点不为空时,即有哈希冲突时,采用synchronized对当前Node节点加锁,再根据链表或红黑树进行修改,修改后释放锁。
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;
}