jdk以前的版本中ConcurrentHashMap采用分段管理加锁的方式(Segment),今天查看1.8版本的ConcurrentHashMap,发现了一些变化,在这里分享一下。
学习编程,本人感觉最重要的思想,否则只能沦为微软、Sun以及其它公司的“忠实用户”。这里只贴出ConcurrentHashMap新版本的put() 方法,废话说多了
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
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
Node
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
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {//最新的只对key对应的第一个元素加锁
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node
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
if ((e = e.next) == null) {
pred.next = new Node
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node
binCount = 2;
if ((p = ((TreeBin
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;
}