LongAdder和AtomicLong比较
public class LongAdderMain {
public static void main(String[] args) throws InterruptedException {
atomicAlongVsLongAdderTest(1, 10000000);
System.out.println("-----------------------------------");
atomicAlongVsLongAdderTest(10, 10000000);
System.out.println("-----------------------------------");
atomicAlongVsLongAdderTest(50, 10000000);
}
private static void atomicAlongVsLongAdderTest(int threadNum, int times)
throws InterruptedException {
long start = System.currentTimeMillis();
long result = longAdderRun(threadNum, times);
System.out.println("LongAdder 线程数: " + threadNum + " 结果: "
+ result + " 耗时: " + (System.currentTimeMillis() - start));
long start1 = System.currentTimeMillis();
long result1 = atomicLongRun(threadNum, times);
System.out.println("AtomicLong 线程数: " + threadNum + " 结果: "
+ result1 + " 耗时: " + (System.currentTimeMillis() - start1));
}
private static Long atomicLongRun(int threadNum, int times)
throws InterruptedException {
AtomicLong counter = new AtomicLong();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < threadNum; i++) {
Thread t = new Thread(() -> {
int j = 0;
while (j < times) {
counter.incrementAndGet();
j++;
}
});
list.add(t);
}
for (Thread thread : list) {
thread.start();
}
for (Thread thread : list) {
thread.join();
}
return counter.get();
}
private static long longAdderRun(int threadNum, int times)
throws InterruptedException {
LongAdder counter = new LongAdder();
List<Thread> list = new ArrayList<>();
for (int i = 0; i < threadNum; i++) {
Thread t = new Thread(() -> {
int j = 0;
while (j < times) {
counter.increment();
//如果每次都取值,longAdder效率不如atomicLong高
// counter.longValue();
j++;
}
});
list.add(t);
}
for (Thread thread : list) {
thread.start();
}
for (Thread thread : list) {
thread.join();
}
return counter.longValue();
}
}
结果:
LongAdder 线程数: 1 结果: 10000000 耗时: 125 ms
AtomicLong 线程数: 1 结果: 10000000 耗时: 108 ms
-----------------------------------
LongAdder 线程数: 10 结果: 100000000 耗时: 137 ms
AtomicLong 线程数: 10 结果: 100000000 耗时: 2153 ms
-----------------------------------
LongAdder 线程数: 50 结果: 500000000 耗时: 338 ms
AtomicLong 线程数: 50 结果: 500000000 耗时: 10134 ms
可以发现, LongAdder的效率还是很高的
LongAdder
实现方式, 相比较AtomicLong, LongAdder 实现不仅仅使用了CAS, 而且也使用了 类似ConcurrentHashMap
分段锁一样的机制:
- Base + Cell[] 数组
- 如果没有线程竞争,result = Base
- 如果存在线程竞争, result = Base+ Cells.value