1. 程式人生 > >LongAdder和AtomicLong性能對比

LongAdder和AtomicLong性能對比

dde auth 提升 0ms zed sum() system oid 運行時間

jdk1.8中新原子操作封裝類LongAdder和jdk1.5的AtomicLong和synchronized的性能對比,直接上代碼:

package com.itbac.cas;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

// 測試用例: 同時運行2秒,檢查誰的次數最多
public class LongAdderDemo {
    // synchronized 方式
    private long count = 0;
    
// Atomic方式 private AtomicLong acount = new AtomicLong(0L); // LongAdder 方式 (jdk1.8,新計數器) private LongAdder lacount = new LongAdder(); // 運行時間,毫秒數 private int time=2000; // 同步代碼塊的方式 public void testSync() throws InterruptedException { for (int i = 0; i < 3; i++) {
new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 運行兩秒 synchronized (this) { ++count; } }
long endtime = System.currentTimeMillis(); System.out.println("SyncThread spend:" + (endtime - starttime) + "ms" + " v:" + count); }).start(); } } public void testAtomic() throws InterruptedException { for (int i = 0; i < 3; i++) { new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 運行兩秒 acount.incrementAndGet(); // acount++; } long endtime = System.currentTimeMillis(); System.out.println("AtomicThread spend:" + (endtime - starttime) + "ms" + " v:" + acount.incrementAndGet()); }).start(); } } public void testLongAdder() throws InterruptedException { for (int i = 0; i < 3; i++) { new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 運行兩秒 lacount.increment(); } long endtime = System.currentTimeMillis(); System.out.println("LongAdderThread spend:" + (endtime - starttime) + "ms" + " v:" + lacount.sum()); }).start(); } } public static void main(String[] args) throws InterruptedException { LongAdderDemo demo = new LongAdderDemo(); demo.testSync(); demo.testAtomic(); demo.testLongAdder(); } }

看看輸出結果:

SyncThread spend:2000ms v:25458554
SyncThread spend:2000ms v:25458554
SyncThread spend:2000ms v:25458554
AtomicThread spend:2000ms v:78489760
AtomicThread spend:2000ms v:78489759
AtomicThread spend:2000ms v:78489758
LongAdderThread spend:2000ms v:141154988
LongAdderThread spend:2000ms v:141154988
LongAdderThread spend:2000ms v:141352859

jdk版本,作者及類名:

* @since 1.5
* @author Doug Lea 
AtomicLong
* @since 1.8
* @author Doug Lea
LongAdder

讓我們來膜拜一下大神!2秒破億次累加。翻倍的性能提升。



LongAdder和AtomicLong性能對比