LongAdder与Atomic*

Atomic类https://blog.****.net/weixin_38336658/article/details/86708083

采用CAS模式来控制安全性

LongAdder类似与ConcurrentHashMap,可以将热点数据分离,相应的速度,性能比Atomic类会好

它有2个方法,add(long x),increment(),sum()

increment()调用的是sum()函数,进行++

最坑的其实是sum函数,源码注解:

LongAdder与Atomic*

在并发环境下会出现错误。

个人理解:LongAdder保证最终一致性,强一致性是保证不了的,所以对于那些需要线程安全、强一致性的,不建议使用。

使用于统计个数,对线程安全要求不高,更新操作不高的场景

个人的demo

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class test4 {
    static test4 t=new test4();
    public static LongAdder longAdder=new LongAdder();
    public static AtomicLong atomicLong=new AtomicLong();
    ConcurrentHashMap concurrentHashMap=new ConcurrentHashMap();

    public static void main(String[] args) {
        longAdder.increment();
        synchronized (t) {
            System.out.println(longAdder.sum());
        }
    }

    public long getNumber(){
        longAdder.increment();
        //long v=atomicLong.incrementAndGet();
        synchronized (t) {
            long v=test4.longAdder.sum();
            if (concurrentHashMap.get(String.valueOf(v)) == null) {
                concurrentHashMap.put(String.valueOf(v), "1");
                System.out.println("插入" + v);
            } else {
                System.out.println(v + "出错...............");
            }
            return v;
        }
        /*if(concurrentHashMap.get(String.valueOf(v))==null) {
            concurrentHashMap.put(String.valueOf(v), "1");
            System.out.println("插入"+v);
        }else {
            System.out.println(v+"出错...............");
        }
        return v;*/
    }
}
public class TestThread implements Runnable{

    test4 t;

    @Override
    public void run() {
        System.out.println(t.getNumber()+" "+"test");
    }

    public  TestThread(test4 t){
        this.t=t;
    }

}
public class test5 {
    public static void main(String[] args) {
        test4 t=new test4();
        for(int i=0;i<100;i++){
            new Thread(new TestThread(t)).start();
        }
    }
}

在最终都是达到100,但是过程就很多出错,所以对于LongAdder还是谨慎使用