volatile 与 LongAdder 的性能差异及替代方案
使用 longadder 替代 volatile 变量可以提升高并发下的累加性能,核心在于减少多线程竞争导致的缓存行伪共享和频繁的全局内存刷新。当多个线程同时修改同一个 volatile long 变量时,cpu 的缓存一致性协议(如 mesi)会导致频繁的缓存失效和重新加载,形成严重的性能瓶颈。而 longadder 通过分段累加(striped accumulation)机制,将竞争分散到多个内部单元上,显著降低了锁竞争和缓存争用。

如何从 volatile 改造为 LongAdder
将代码中的 volatile long 替换为 LongAdder 实例,并将所有的自增操作(如 ++count)改为调用 add(1) 方法,读取值时调用 sum() 方法即可。这种改造不需要改变业务逻辑,只需调整数据结构和原子操作的方式。需要注意的是,LongAdder 的 sum() 方法返回的是所有分段的总和,其结果在并发环境下是最终一致性的,但在累加过程中可能不是实时精确的,这通常是可以接受的权衡。

import java.util.concurrent.atomic.LongAdder;
public class VolatileToLongAdderExample {
// 旧写法:volatile long count = 0;
// 新写法:
private final LongAdder count = new LongAdder();
public void increment() {
// 旧写法:count++;
// 新写法:
count.add(1);
}
public long getCount() {
// 旧写法:return count;
// 新写法:
return count.sum();
}
public static void main(String[] args) throws InterruptedException {
VolatileToLongAdderExample example = new VolatileToLongAdderExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
example.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + example.getCount());
}
}为什么 LongAdder 在高竞争下更快
LongAdder 之所以快,是因为它使用了“空间换时间”的策略,将单个变量的更新压力分散到多个单元格(Cell)中。每个线程在累加时,会尝试更新自己所在的 Cell,如果发生冲突,才会尝试更新 base 变量或扩容 Cell 数组。这种设计避免了所有线程都去争夺同一个内存地址的缓存行,从而大幅提升了吞吐量。相比之下,volatile 变量虽然保证了可见性,但每次写操作都会触发缓存同步,导致其他 CPU 核心的缓存失效,这在多核高并发场景下是致命的性能杀手。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.atomic.LongAdder;
public class PerformanceComparison {
public static void main(String[] args) {
int threadCount = 10;
int iterations = 1000000;
// 测试 volatile
long startVolatile = System.nanoTime();
testVolatile(threadCount, iterations);
long endVolatile = System.nanoTime();
System.out.println("Volatile Time: " + (endVolatile - startVolatile) / 1_000_000 + " ms");
// 测试 LongAdder
long startLongAdder = System.nanoTime();
testLongAdder(threadCount, iterations);
long endLongAdder = System.nanoTime();
System.out.println("LongAdder Time: " + (endLongAdder - startLongAdder) / 1_000_000 + " ms");
}
private static void testVolatile(int threads, int iterations) throws InterruptedException {
volatile long count = 0;
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) {
ts[i] = new Thread(() -> {
for (int j = 0; j < iterations; j++) {
count++; // 高竞争
}
});
ts[i].start();
}
for (Thread t : ts) t.join();
}
private static void testLongAdder(int threads, int iterations) throws InterruptedException {
LongAdder count = new LongAdder();
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) {
ts[i] = new Thread(() -> {
for (int j = 0; j < iterations; j++) {
count.add(1); // 低竞争
}
});
ts[i].start();
}
for (Thread t : ts) t.join();
}
}



















