首页   快速返回

LongAdder vs AtomicLong     所属分类 java 浏览量 26
This class is usually preferable to AtomicLong 
when multiple threads update a common sum that is used for purposes such as collecting statistics, 
not for fine-grained synchronization control.  
Under low update contention, the two classes have similar characteristics. 
But under high contention, expected throughput of this class is significantly higher,
at the expense of higher space consumption.
 
 
LongAdder 把 value 分成若干cell  并发高时,CAS更新某个cell值 ,需要时对cell扩容。取值时,调用 sum() 方法进行每个cell累加。

低并发场景AtomicLong 和 LongAdder 性能相似,高并发场景 LongAdder 性能优于 AtomicLong


    public void add(long x) {
        Cell[] as; long b, v; int m; Cell a;
        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);
        }
    }
    
    public void increment() {
        add(1L);
    }
    
    public void decrement() {
        add(-1L);
    }
    
    public long sum() {
        Cell[] as = cells; Cell a;
        long sum = base;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null)
                    sum += a.value;
            }
        }
        return sum;
    }

上一篇     下一篇
spring循环依赖

Java实用工具类

mysql索引失效的几种情况

map computeIfAbsent 方法使用

微服务架构优雅停机

基本的社交礼仪