解答
                
                addCount(),它会先对 CHM 中所有键值对计数,然后考虑是否扩容。现在我们来看看它是如何计数的。
private final void addCount(long x, int check) {
    CounterCell[] as; long b, s;
    // 第一层if
    if ((as = counterCells) != null ||
        !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
        CounterCell a; long v; int m;
        boolean uncontended = true;
        // 第二层if
        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();
    }
    if (check >= 0) {
        ...
    }
}addCount() 中有两层 if,其中蕴含了非常巧妙的设计,第一层:
counterCells 不为空:跳转第二层 if;
counterCells 为空:不着急创建 counterCells,先用原子操作增加 baseCount:
成功:结束计数;
失败:跳转第二层 if。
第二层 if 就是用来创建 counterCells 以及使用它来计数的:
counterCells 为空或 counterCells[probe] 为空:调用 fullAddCount(x, true);
counterCells[probe] 已经创建:原子操作增加其 value 值:
成功:结束计数;
失败:调用 fullAddCount(x, false)。
 
             
                 
                            
 
                    
帖子还没人回复快来抢沙发