一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第25天,点击查看活动详情。
ConcurrentHashMap 源码分析-put()
ConcurrentHashMap 的 put 方法与 HashMap 几乎相同,只是多出了线程安全的保障相关代码。源码:
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;
}
int hash = spread(key.hashCode()); 计算hash
if (tab == null || (n = tab.length) == 0) tab = initTable(); table是空的,进行初始化
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { }如果当前索引位置没有值,直接创建
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; cas 在 i 位置创建新的元素,当 i 位置是空时,即能创建成功,结束for自循,否则继续自旋
else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f);如果当前槽点是转移节点,表示该槽点正在扩容,就会一直等待扩容完成,转移节点的 hash 值是固定的,都是 MOVED
synchronized (f) { } 锁定当前槽点,其余线程不能操作,保证了安全
if (tabAt(tab, i) == f) { } 这里再次判断 i 索引位置的数据没有被修改,binCount 被赋值的话,说明走到了修改表的过程里面
if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { 有值的话,直接返回
if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } 把新增的元素赋值到链表的最后,退出自旋
else if (f instanceof TreeBin) { } TreeBin 持有红黑树的引用,并且会对其加锁,保证其操作的线程安全
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; }满足if的话,把老的值给oldVal,在putTreeVal方法里面,在给红黑树重新着色旋转的时候,会锁住红黑树的根节点
if (binCount != 0) { } binCount不为空,并且 oldVal 有值的情况,说明已经新增成功了
if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i);链表是否需要转化成红黑树
addCount(1L, binCount); check 容器是否需要扩容,如果需要去扩容,调用 transfer 方法去扩容,如果已经在扩容中了,check有无完成