项目场景:
使用LongAdder本地保存数据,定时的去拉取本地缓存中的数据更新到数据库。
虽然LongAdder的性能比AtomicInteger更好,但是LongAdder获取的值不是准确值
累加器性能比较
public class Test41 {public static void main(String[] args) {for (int i = 0; i < 5; i++) {demo(() -> new AtomicLong(0),(adder) -> adder.getAndIncrement());}for (int i = 0; i < 5; i++) {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 j = 0; j < 500000; j++) {action.accept(adder);}}));}long start = System.nanoTime();ts.forEach(t -> t.start());ts.forEach(t -> {try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});long end = System.nanoTime();System.out.println(adder + " cost:" + (end - start) / 1000_000);}}
2000000 cost:35 2000000 cost:29 2000000 cost:32 2000000 cost:33 2000000 cost:30 2000000 cost:9 2000000 cost:5 2000000 cost:5 2000000 cost:4 2000000 cost:3
