为什么AtomicInteger等等有累加的方法,还需要另外搞一个原子累加器?因为原子累加器性能高
package com.sharing_model.no_lock;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* 原子累加器: Atomic accumulator
*/
/**
* 使用累加器和原子类自带的累加效率进行比较
* 为什么性能更高,很简单,就是在有竞争时,同时设置多个累加单元,Thread-0累加Cell[0], 而Thread-1累加Cell[1]..
* 最后将结果汇总。这样它们在累加的时操作的不同的Cell变量,因此减少了CAS重试失败,从而提高性能。
*/
public class AtomicAccumulatorTest {
public static void main(String[] args) {
//使用自带的 AtomicLong
demo(
() -> new AtomicLong(0),
(adder) -> adder.getAndIncrement()
);
//使用累加器 LongAdder
demo(
() -> new LongAdder(),
adder -> adder.increment()
);
}
private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
T adder = adderSupplier.get();
List<Thread> ts = new ArrayList<>();
//4个线程,没人累加50万
for (int i = 0; i < 4; i++) {
ts.add(new Thread(() -> {
for (int k = 0; k < 500 * 1000; k++) {
action.accept(adder);
}
}));
}
long start = System.nanoTime();
ts.forEach(t -> t.start());
ts.forEach(t -> {});
long end = System.nanoTime();
System.out.println(adder + " cost:" + (end -start)/1000_000);
}
}