一、前言
本文对AtomicLong和LongAdder 性能测试。
在Java中,线程部分是一个重点,JUC中使用CAS算法来实现同步,这是一种乐观锁(JDK 5之前Java语言是靠synchronized关键字保证同步的,这是一种独占锁,也是是悲观锁)。
JUC:java.util .concurrent工具包的简称。这是一个处理线程的工具包,JDK 1.5开始出现的。
CAS:Compare and Swap,即比较再交换。
AtomicLong:是一个提供原子操作的Integer类,通过线程安全的方式操作加减。
LongAdder :是一个多线程高并发时使用的自增计数器,它的设计思想就是以空间换时间。
AtomicLong在进行incrementAndGet源码解析的时候,在高并发之下,N多线程进行自旋竞争同一个字段,这无疑会给CPU造成一定的压力,所以在Java8中,提供了更完善的原子操作类:LongAdder。
二、环境
Windows 10专业版
java version "1.8.0_77"
Ite(R) CofM15-9400CPU@ 29CHz 2.90GHz
三、源码
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
/**
* 并发计数器:AtomicLong和LongAdder性能测试
* 使用倒计时器:CountDownLatch来做耗时统计
*/
public class Test2 {
private static Integer integer = 0;
private static final Integer THREAD_NUM = 50;//线程数
private static final Integer COUNT = 100 * 10000;//每个线程计数次数
private static LongAdder longAdder = new LongAdder();
private static AtomicLong atomicLong = new AtomicLong();
public static void main(String[] args) throws InterruptedException {
// testLongAdder();
testAtomicLong();
}
private static void testAtomicLong() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
long start = System.currentTimeMillis();
long a = 1L;
for (int i = 0; i < THREAD_NUM; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
for (int j = 0; j < COUNT; j++) {
atomicLong.incrementAndGet();
}
} finally {
countDownLatch.countDown();
}
}
});
thread.start();
}
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println("testAtomicLong结果" + atomicLong + "耗时:" + (end - start) + "毫秒");
}
private static void testLongAdder() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
long start = System.currentTimeMillis();
for (int i = 0; i < THREAD_NUM; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
for (int j = 0; j < COUNT; j++) {
longAdder.add(1L);
}
} finally {
countDownLatch.countDown();
}
}
});
thread.start();
}
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println("testLongAdder结果" + longAdder + "耗时:" + (end - start) + "毫秒");
}
}
四、结果分析
通过设置不同的THREAD_NUM和COUNT统计程序耗时做性能测试
参数设置 | AtomicLong耗时(ms) | LongAdder耗时(ms) |
THREAD_NUM=10 COUNT=10*10000 | 25 | 26 |
THREAD_NUM=20 COUNT=100*10000 | 341 | 75 |
THREAD_NUM=50 COUNT=100*10000 | 840 | 118 |
从程序耗时得出结论:
LongAdder在线程数多,计数次数多的时候性能更好。