跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • ConcurrentHashMap#addCount() 为什么只要 CAS 失败了,就肯定不扩容了?
未分類
21 7 月 2020

ConcurrentHashMap#addCount() 为什么只要 CAS 失败了,就肯定不扩容了?

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)

  • 資深大佬 : jasonyee

    CAS 失败说明被其他线程扩容了 就不需要本线程操作了

  • 主 資深大佬 : amiwrong123

    @jasonyee
    比如这种场景,线程 A CAS 成功,此时大小为阈值-1 ;然后线程 B CAS 失败,之后执行 fulladdcount 后大小刚好为阈值,但由于失败,不会去扩容;只有等到第 3 个线程到来,才可能去扩容了。

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具