LongAdder的属性
// 累加单元数组, 懒惰初始化transient volatile Cell[] cells;// 基础值, 如果没有竞争, 则用 cas 累加这个域transient volatile long base;// 在 cells 创建或扩容时, 置为 1, 表示加锁transient volatile int cellsBusy;
Cell 累加单元
// 防止缓存行伪共享@sun.misc.Contendedstatic final class Cell { volatile long value; Cell(long x) { value = x; } // 最重要的方法, 用来 cas 方式进行累加, prev 表示旧值, next 表示新值 final boolean cas(long prev, long next) { return UNSAFE.compareAndSwapLong(this, valueOffset, prev, next); } // 省略不重要代码}
AtomicLong与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); }}
