ConcurrentHashMap#addCount() 为什么只要 CAS 失败了,就肯定不扩容了?
資深大佬 : amiwrong123 6
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))) { //执行到这里,要么 CAS 修改 baseCount 失败了,要么 CAS 修改某个 cell 的值失败了 //之后将直接 return fullAddCount(x, uncontended); return; } if (check <= 1) return; s = sumCount(); } //扩容部分 if (check >= 0) { Node<K,V>[] tab, nt; int n, sc; while (s >= (long)(sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { int rs = resizeStamp(n); if (sc < 0) { if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) break; if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) transfer(tab, nt); } else if (U.compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) transfer(tab, null); s = sumCount(); } } }
就是不大理解这个意思。
这样的做法,岂不是会导致,该扩容的时候不会扩容。因为毕竟只有 CAS 直接成功的线程,才可能扩容。
大佬有話說 (2)