AtomicLong VS Sync VS LongAdder

x33g5p2x  于2021-12-18 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(284)

AtomicLong VS Sync VS LongAdder

public class T02_AtomicVsSyncVsLongAdder {
    static AtomicLong count1 = new AtomicLong(0L);
    static Long count2 = 0L;
    static LongAdder count3 = new LongAdder();

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[1000];
        long start, end;

        // AtomicLong
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100000; j++) count1.incrementAndGet();
            });
        }
        start = System.currentTimeMillis();
        for (Thread thread : threads) thread.start();
        for (Thread thread : threads) thread.join();
        end = System.currentTimeMillis();
        System.out.println("Atomic " + count1 + " time " + (end - start));

        // long
        final Object lock = new Object();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 100000; j++) {
                        synchronized (lock) {
                            count2++;
                        }
                    }
                }
            });
        }
        start = System.currentTimeMillis();
        for (Thread thread : threads) thread.start();
        for (Thread thread : threads) thread.join();
        end = System.currentTimeMillis();
        System.out.println("Sync " + count2 + " time " + (end - start));

        // LongAdder
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    count3.increment();
                }
            });
        }
        start = System.currentTimeMillis();
        for (Thread thread : threads) thread.start();
        for (Thread thread : threads) thread.join();
        end = System.currentTimeMillis();
        System.out.println("LongAdder " + count3 + " time " + (end - start));
    }
}

// 控制台输出如下
Atomic      100000000 time 944
Sync        100000000 time 7446
LongAdder   100000000 time 878

Atmoic 原子类是通过 CAS 算法实现的。

LongAdder 为什么最快?LongAdder 内部通过分段锁实现,在线程数特别多的时候很有优势。

相关文章