结论:500个线程做十万次累加,synchronized+volatile操作效率差不多是AtomicInteger的一半,LongAdder和LongAccumulate差不多少是AtomicInteger9分之一,LongAdder所以被阿里java规范推荐使用,NB!
结果展示:
完整可运行代码:
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
@Data
@NoArgsConstructor
@Setter
@Getter
class AcumulateEfficiencyComparsion{
private volatile int i=0;
public void atomicIntegerEfficiency( AtomicInteger atomicInteger){
atomicInteger.getAndIncrement();
}
public synchronized void synIncreament(){
++i;
}
public void longAdderTets(LongAdder longAdder){
longAdder.increment();
}
public void longAccumulatorTest( LongAccumulator accumulator){
accumulator.accumulate(1);
}
}
public class AccumulateTest {
public static void main(String[] args) throws InterruptedException {
int SIZE_=500;
Long start;
Long end;
AcumulateEfficiencyComparsion aec=new AcumulateEfficiencyComparsion();
start=System.currentTimeMillis();
CountDownLatch countDownLatch1=new CountDownLatch(SIZE_);
for (int i = 0; i < SIZE_; i++) {
new Thread(()->{
for (int j = 0; j <100000 ; j++) {
aec.synIncreament();
}
countDownLatch1.countDown();
}).start();
}
countDownLatch1.await();
end=System.currentTimeMillis();
System.out.println("synchronized+volatile强锁:" +(end-start)+"----->"+aec.getI());
start=System.currentTimeMillis();
CountDownLatch countDownLatch=new CountDownLatch(SIZE_);
AtomicInteger atomicInteger=new AtomicInteger(0);
for (int i = 0; i < SIZE_; i++) {
new Thread(()->{
for (int j = 0; j <100000 ; j++) {
aec.atomicIntegerEfficiency(atomicInteger);
}
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
end=System.currentTimeMillis();
System.out.println("AtomicInteger:" +(end-start)+"----->"+atomicInteger.get());
start=System.currentTimeMillis();
CountDownLatch countDownLatch2=new CountDownLatch(SIZE_);
LongAdder longAdder=new LongAdder();
for (int i = 0; i < SIZE_; i++) {
new Thread(()->{
for (int j = 0; j <100000 ; j++) {
aec.longAdderTets(longAdder);
}
countDownLatch2.countDown();
}).start();
}
countDownLatch2.await();
end=System.currentTimeMillis();
System.out.println("LongAdder:" +(end-start)+"----->"+longAdder.sum());
start=System.currentTimeMillis();
CountDownLatch countDownLatch3=new CountDownLatch(SIZE_);
LongAccumulator accumulator=new LongAccumulator((l,f)->l+f,0);
for (int i = 0; i < SIZE_; i++) {
new Thread(()->{
for (int j = 0; j <100000 ; j++) {
aec.longAccumulatorTest(accumulator);
}
countDownLatch3.countDown();
}).start();
}
countDownLatch3.await();
end=System.currentTimeMillis();
System.out.println("LongAccumulator:" +(end-start)+"----->"+accumulator.get());
}
}