并发--性能调优(一) 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相对比较一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值