并发性能优化之使用LongAdder替换AtomicLong
因为计数器操作涉及到内存的可见性和线程之间的竞争,而Atomic*的实现完美的屏蔽了这些技术细节,我们只需要执行相应的方法,就能实现对应的业务需求。
Atomic虽然好用,不过这些的操作在并发量很大的情况下,性能问题也会被相应的放大。我们可以先看下其中getAndIncrement的实现代码
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(Mode.Throughput)
public class Main {
private static AtomicLong count = new AtomicLong();
private static LongAdder longAdder = new LongAdder();
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(Main.class.getName()).forks(1).build();
new Runner(options).run();
}
@Benchmark
@Threads(10)
public void run0(){
count.getAndIncrement();
}
@Benchmark
@Threads(10)
public void run1(){
longAdder.increment();
}
}
LongAdder的吞吐量比较大,也是AtomicLong的10倍多。
LongAdder的平均耗时也是AtomicLong的十分之一。