前言
在JDK1.5开始就新增了并发的Integer/Long的操作工具类AtomicInteger和AtomicLong。在JDK8中又新增了LongAdder,这是一个针对Long类型的数据的操作工具类。
那么既然已经有了AtomicLong,为何又要新增LongAdder这么一个类呢?
LongAdder的实现原理
我们知道,AtomicLong的实现原理是:利用底层操作系统的CAS来保证原子性,在一个死循环内不断执行CAS操作,直到操作成功。不过,CAS操作的一个问题是在并发量比较大的时候,可能很多次的执行CAS操作都不成功,这样性能就受到较大影响。
那我们知道,在ConcurrentHashMap中,对Map分割成多个segment,这样多个Segment的操作就可以并行执行,从而可以提高性能。在JDK8中,LongAdder与ConcurrentHashMap类似,将内部操作数据value分离成一个Cell数组,每个线程访问时,通过Hash等算法映射到其中一个Cell上。
计算最终的数据结果,则是各个Cell数组的累计求和。
LongAdder提供的方法
- add():增加指定的数值;
- increament():增加1;
- decrement():减少1;
- intValue()/floatValue()/doubleValue():得到最终计数后的结果
- sum():求和,得到最终计数结果
- sumThenReset():求和得到最终计数结果,并重置value。
示例代码
public class LongAdderTest {
static java.util.concurrent.atomic.LongAdder count = new LongAdder();
static class AddThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
count.increment();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new AddThread());
Thread t2 = new Thread(new AddThread());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count.intValue() == 200000);
}
}
注意事项
在并发较低时LongAdder使用casBase()方法直接修改value,以达到和AtomicLong基本相当的性能;在并发较高时,自动拆分为Cell数组,并自动扩容,分散热点,以保证性能。
LongAdder原理分析:https://blog.csdn.net/u011392897/article/details/60480108
LongAdder与AtomicLong性能对比测试:https://blog.csdn.net/li396864285/article/details/78246357