longAdder原理

通过数组与值实现,看源码

public void add(long x) {
    Cell[] as; long b, v; int m; Cell a;
    
    // 尝试直接通过CAS操作累加base的值  
    // 如果cells数组不为null,或者通过CAS操作未能成功累加base的值  
    
    //相当于是更新base值,如果失败了就去更新Cell数组
    if ((as = cells) != null || !casBase(b = base, b + x)) {
        boolean uncontended = true;
        if (as == null || (m = as.length - 1) < 0 ||
            (a = as[getProbe() & m]) == null ||
            !(uncontended = a.cas(v = a.value, v + x)))
            longAccumulate(x, null, uncontended);
    }
}
posted @ 2024-08-15 18:24  辉辉、  阅读(13)  评论(0)    收藏  举报