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 直接成功的线程,才可能扩容。
1
jasonyee 2020-07-12 23:46:01 +08:00 via iPhone
CAS 失败说明被其他线程扩容了 就不需要本线程操作了
|
2
amiwrong123 OP @jasonyee
比如这种场景,线程 A CAS 成功,此时大小为阈值-1 ;然后线程 B CAS 失败,之后执行 fulladdcount 后大小刚好为阈值,但由于失败,不会去扩容;只有等到第 3 个线程到来,才可能去扩容了。 |