併發--性能調優(一) Synchronized Lock Atomic類比較

性能調優

  1. 互斥技術。 Synchronized Lock Atomic類比較

  2. Synchronized 和Lock簡單性能測試

package com21併發1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Panda on 2018/5/28.
 */

//簡單性能測試
abstract class Incrementable {
    protected long counter = 0;

    public abstract void increment();
}

class SynchronizingTest extends Incrementable {
    @Override
    public synchronized void increment() {
        ++counter;
    }
}

class LockingTest extends Incrementable {
    private Lock lock = new ReentrantLock();

    @Override
    public void increment() {
        lock.lock();
        try {
            ++counter;
        } finally {
            lock.unlock();
        }
    }
}

public class SimpleBenchmark {
    static long test(Incrementable incrementable) {
        long start = System.nanoTime();
        for (long i = 0; i < 10000000L; i++) {
            incrementable.increment();
        }
        return System.nanoTime() - start;
    }

    public static void main(String[] args) {
        long synchTime =test(new SynchronizingTest());
        long lockTime=test(new LockingTest());
        System.out.printf("synchronized: %1$10d\n",synchTime);
        System.out.printf("Lock:         %1$10d\n",lockTime);
        System.out.printf("Lock/synchronized=%1$.3f",(double)lockTime/(double)synchTime);
    }
    /**
     * 
     synchronized:  484074463
     Lock:          384949090
     Lock/synchronized=0.795
     */
}

3.複雜性測試

package com21併發1;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Panda on 2018/5/28.
 */
abstract class Accumulaor {
    public static long cycles = 50000L;
    private static final int N = 4;
    public static ExecutorService executorService = Executors.newFixedThreadPool(2 * N);
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2 * N + 1);
    protected volatile int index = 0;
    protected volatile long value = 0;
    protected long duration = 0;
    protected String id = "error";
    protected final static int SIZE = 100000;
    protected static int[] preLoaded = new int[SIZE];

    static {
        Random random = new Random(47);
        for (int i = 0; i < SIZE; i++) {
            preLoaded[i] = random.nextInt();
        }
    }

    public abstract void accumulate();

    public abstract long read();

    private class Modifier implements Runnable {
        @Override
        public void run() {
            for (long i = 0; i < cycles; i++)
                accumulate();
            try {
                cyclicBarrier.await();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private class Reader implements Runnable {
        @Override
        public void run() {
            for (long i = 0; i < cycles; i++)
                value = read();
            try {
                cyclicBarrier.await();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void timedTest() {
        long start = System.nanoTime();
        for (int i = 0; i < N; i++) {
            executorService.execute(new Modifier());
            executorService.execute(new Reader());
        }
        try {
            cyclicBarrier.await();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        duration = System.nanoTime() - start;
        System.out.printf("%-13s: %13d\n", id, duration);
    }

    public static void report(Accumulaor accumulaor1, Accumulaor accumulaor2) {
        System.out.printf("%-22s: %.2f\n", accumulaor1.id + "/" + accumulaor2.id,
                (double) accumulaor1.duration / (double) accumulaor2.duration);
    }
}

class BaseLine extends Accumulaor {
    {
        id = "BaseLine";
    }

    @Override
    public void accumulate() {
        value += preLoaded[index++];
        if (index >= SIZE) index = 0;
    }

    @Override
    public long read() {
        return value;
    }
}

class SynchronizedTest extends Accumulaor {
    {
        id = "synchronized";
    }

    @Override
    public synchronized void accumulate() {
        value += preLoaded[index++];
        if (index >= SIZE) index = 0;
    }

    @Override
    public synchronized long read() {
        return value;
    }
}

class LockTest extends Accumulaor {
    {
        id = "Lock";
    }

    private Lock lock = new ReentrantLock();

    @Override
    public void accumulate() {
        lock.lock();
        try {
            value += preLoaded[index++];
            if (index >= SIZE) index = 0;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public long read() {
        lock.lock();
        try {
            return value;
        } finally {
            lock.unlock();
        }
    }
}

class AtomicTest extends Accumulaor {
    {
        id = "Atomic";
    }

    private AtomicInteger index = new AtomicInteger(0);
    private AtomicLong value = new AtomicLong(0);

    @Override
    public void accumulate() {
        int i = index.getAndIncrement();
        value.getAndAdd(preLoaded[i]);
        if (++i >= SIZE) index.set(0);
    }

    @Override
    public long read() {
        return value.get();
    }
}


public class SynchronizationComparisons {
    static BaseLine baseLine = new BaseLine();
    static SynchronizedTest synchronizedTest = new SynchronizedTest();
    static LockTest lockTest = new LockTest();
    static AtomicTest atomicTest = new AtomicTest();

    static void test() {
        System.out.println("===================================");
        System.out.printf("%-12s ; %13d\n", "Cycles", Accumulaor.cycles);
        baseLine.timedTest();
        synchronizedTest.timedTest();
        lockTest.timedTest();
        atomicTest.timedTest();
        Accumulaor.report(synchronizedTest, baseLine);
        Accumulaor.report(lockTest, baseLine);
        Accumulaor.report(atomicTest, baseLine);
        Accumulaor.report(synchronizedTest, lockTest);
        Accumulaor.report(synchronizedTest, atomicTest);
        Accumulaor.report(lockTest, atomicTest);
    }

    public static void main(String[] args) {
        int iterations = 5;
        if (args.length > 0) iterations = new Integer(args[0]);
        System.out.println("Warmup");
        baseLine.timedTest();
        for (int i = 0; i < iterations; i++) {
            test();
            Accumulaor.cycles *= 2;
        }

        Accumulaor.executorService.shutdown();
    }
    /** demo 有點問題 數組下標越界
     * Warmup
     BaseLine     :      39581645
     ===================================
     Cycles       ;         50000
     BaseLine     :      26996159
     synchronized :      81296625
     Lock         :      55670146
     */
}

解釋:使用Lock通常會比使用synchronized要高效許多,而且Synchronized的開銷變化範圍比較大,而Lock相對比較一致。

發佈了64 篇原創文章 · 獲贊 1 · 訪問量 6737
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章