JAVA并发之ConcurrentHashMap源码分析
HashMap并不能在多线程下保证数据安全,为了适应并发场景JUC包下提供了ConcurrentHashMap。
ConcurrentHashMap与HashMap比较相似,底层都是数组+链表+红黑树。其最大区别体现在put方法中。
保证HashMap的线程安全,就是保证hashMap的数据的线程安全,其数据包括、底层维护的数组、链表、红黑树以及map的size的线程安全。带着这个思路,可以很清楚地看懂ConcurrentHashMap源码。
ConcurrentHashMap保证size的线程安全的方式
方式:在多线程的场景下,size会出现脏读的问题,导致size与实际数据数量不相等的情况,正常思路下,直接在size++上加上一把锁就可以解决这个问题,这是没错的,但是加入线程很多,太多线程争抢一个锁的难度是很高的。所以ConcurrentHashMap直接增加了好几把锁,平均分给线程(并非平均,有算法控制),这样让争抢锁的难度减低了,即分流。
ConcurrentHashMap是通过一个动态数组counterCells来实现的,大致思路如下每个线程进入addCount方法之后会调用(ThreadLocalRandom.getProbe() & m)这个算法随机分配一个桶位,然后通过CAS修改下标是(ThreadLocalRandom.getProbe() & m)的值,其实就是加一操作。这样就实现了多把锁的分配,这时size是有counterCells数组的所有值相加。数组大小可以进行扩容,初始化是2;
代码如下
/**
addCount方法会进行两个操作,一个是扩容,另一个就是上面讲的维护size的线程安全,这里将扩容代码删除了,其核心在fullAddCount方法中
*/
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
}
//维护counterCells数组
private final void fullAddCount(long x, boolean wasUncontended) {
int h;
if ((h = ThreadLocalRandom.getProbe()) == 0) {
ThreadLocalRandom.localInit(); // force initialization
h = ThreadLocalRandom.getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
CounterCell[] as; CounterCell a; int n; long v;
//此时数组初始化完成
if ((as = counterCells) != null && (n = as.length) > 0) {
//此时线程分配的桶位是第一次使用
if ((a = as[(n - 1) & h]) == null) {
//cellsBusy == 0表示erCells不在初始化或者扩容状态下
if (cellsBusy == 0) { // Try to attach new Cell
CounterCell r = new CounterCell(x); // Optimistic create
//CAS色设置cellsBusy,防止并发线程干扰
if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean created = false;
try { // Recheck under lock
//在桶位赋值
CounterCell[] rs; int m, j;
if ((rs = counterCells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
cellsBusy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
//线程CAS失败,继续自旋
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
//指定的桶位有数据直接CAS增加数组
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
//
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
//数组需要扩容
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
//建立新数组,扩容2倍
CounterCell[] rs = new CounterCell[n << 1];
//保存原先数据到新组中
for (int i = 0; i < n; ++i)
rs[i] = as[i];
counterCells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = ThreadLocalRandom.advanceProbe(h);
}
//未被初始化,进行初始化
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
//初始化,默认数组大小为2
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
ConcurrentHashMap保证数据的线程安全的方式
维护数据线程安全,ConcurrentHashMap当然也不仅仅是加一个锁这么简单,处理思路如下:
当没有hash冲突时,直接CAS自旋放置,因为此时只需要有一个线程成功。
当遇到hash冲突时,会将整个操作加上锁,但是并没有锁住整个数组,而是只锁住了需要的桶位。再进行链或者树操作,只是比hashMap多了一个交给用户的是否覆盖相同值的操作。
//第一次,初始化数组
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//数组桶位的值为空,直接CAS放入
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;
}
}
ConcurrentHashMap保证扩容安全
因为为了此时加锁的地方只是数组的桶位,而不是整个数组,因此,还要额外考虑数据的扩容安全
ConcurrentHashMap的扩容设计的很奇妙,多个线程可以一起帮助扩容,具体实现如下代码:
当保存数据量超出阈值是会进行扩容操作,这个判断在addCount()方法里面,其他线程再进行put操作时,会判断当前的槽位是否在扩容,如果在就帮助扩容,在helpTransfer()方法检查满足帮助扩容的条件是否达到,再进行扩容,第一个进来扩容的线程建好2倍于旧数组大小的新数组,扩容时,每个线程会平均分到一个小的工作区域,各自只转移自己的区域部分的值。
SIZECTL字段的作用:
-1 :代表table正在初始化,其他线程应该交出CPU时间片
-N: 表示正有N-1个线程执行扩容操作(高 16 位是 length 生成的标识符,低 16 位是扩容的线程数)
大于 0: 如果table已经初始化,代表table阈值,默认为table大小的0.75,如果还未初始化,代表需要初始化的大小
//如果有线程再进行扩容,当前线程可以进行帮助扩容
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
//如果数组不是空,需要插值的桶位是需要转移的
//并且新的数组已经被创建好了
//可以尝试帮助扩容
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
//得到老table的一个标识符
int rs = resizeStamp(tab.length);
//确认是否还是需要扩容
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
//校验是否满足参加扩容的条件
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
//CAS将sizeCtl +1,提示多了一个线程参加扩容操作中
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
private final void transfer(ConcurrentHashMap.Node<K,V>[] tab, ConcurrentHashMap.Node<K,V>[] nextTab) {
int n = tab.length, stride;
//是否是单核环境,单核环境就分16,多核环境通过数组长度/8/核心树,如果小于16就分16个,如果不是就分计算结果那么多个
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
//如果当前是第一次扩容,即扩容数组没有初始化
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
//初始化为2倍原数组
ConcurrentHashMap.Node<K,V>[] nt = (ConcurrentHashMap.Node<K,V>[])new ConcurrentHashMap.Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
transferIndex = n;
}
//得到扩容数组的长度
int nextn = nextTab.length;
//创建一个fwd节点,表示一个正在迁移的Node
ConcurrentHashMap.ForwardingNode<K,V> fwd = new ConcurrentHashMap.ForwardingNode<K,V>(nextTab);
//转移操作的初始化,当当前槽位的数据全部转移完成就变为false
boolean advance = true;
//扩容完成标志位
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
ConcurrentHashMap.Node<K,V> f; int fh;
//循环转移数据
while (advance) {
int nextIndex, nextBound;
//当处理完成全部槽位,跳出循环
if (--i >= bound || finishing)
advance = false;
//表示此时所有的转移任务都有一个线程处理了,就不需要本线程了
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
//得到i->当前处理的槽位,bound->处理的边界槽位
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
//如果不需要本线程转移,或者已经转移了所有的数据
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//如果整个数组扩容已经结束了
if (finishing) {
nextTable = null;
//数组赋值
table = nextTab;
//新的阈值
sizeCtl = (n << 1) - (n >>> 1);
return;
}
//如果仅仅只是本线程的扩容任务结束了
//SIZECTL-1,表示一个线程处理结束
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
//第一个扩容的线程,执行transfer方法之前,会设置 sizeCtl = (resizeStamp(n) << RESIZE_STAMP_SHIFT) + 2)
//后续帮其扩容的线程,执行transfer方法之前,会设置 sizeCtl = sizeCtl+1
//每一个退出transfer的方法的线程,退出之前,会设置 sizeCtl = sizeCtl-1
//如果是最后一个线程完成,就代表整个数组扩容结束,就返回
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
//如果当前槽位没有数据,直接标记为fwd
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
//如果已经有线程转移过当前节点,就直接标记
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
//如果不为空
else {
//槽位锁
synchronized (f) {
//高低位分离转移
if (tabAt(tab, i) == f) {
ConcurrentHashMap.Node<K,V> ln, hn;
if (fh >= 0) {
int runBit = fh & n;
ConcurrentHashMap.Node<K,V> lastRun = f;
for (ConcurrentHashMap.Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
}
else {
hn = lastRun;
ln = null;
}
for (ConcurrentHashMap.Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new ConcurrentHashMap.Node<K,V>(ph, pk, pv, ln);
else
hn = new ConcurrentHashMap.Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
else if (f instanceof ConcurrentHashMap.TreeBin) {
ConcurrentHashMap.TreeBin<K,V> t = (ConcurrentHashMap.TreeBin<K,V>)f;
ConcurrentHashMap.TreeNode<K,V> lo = null, loTail = null;
ConcurrentHashMap.TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (ConcurrentHashMap.Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
ConcurrentHashMap.TreeNode<K,V> p = new ConcurrentHashMap.TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new ConcurrentHashMap.TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new ConcurrentHashMap.TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
//转移结束,标记该位置已经处理结束
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}