From building distributed systems to talk to spike why not synchronized

Foreword

Technology no ranking points, for his is the best. Only working to expand the boundaries of their knowledge, in order to explore the more uncharted territory.

Case

Before analyzing why not synchronized this question, we first talk in code, LockDemo test case:

/**
 * 案例测试
 * @author 
 */
public class LockDemo {

    private static Lock lock = new ReentrantLock();

    private static int num1 = 0;
    private static int num2 = 0;
    public static void main(String[] args) {
        lockDemo();
        SyncDemo();
    }
    /**
     * 本机测试下20万自增基本能确定性能,但是不是特别明显,50万差距还是挺大的
     * 20万以下数据synchronized优于Lock
     * 20万以上数据Lock优于synchronized
     */
    public static void lockDemo(){
        long start = System.currentTimeMillis();
        for(int i=0;i<500000;i++){
            final int num = i;
            new Runnable() {
                @Override
                public void run() {
                    lock(num);
                }
            }.run();
        }
        long end = System.currentTimeMillis();
        System.out.println("累加:"+num1);
        System.out.println("ReentrantLock锁:"+ (end-start));
    }
    public static void SyncDemo(){
        long start = System.currentTimeMillis();
        for(int i=0;i<500000;i++){
            final int num = i;
            new Runnable() {
                @Override
                public void run() {
                    sync(num);
                }
            }.run();
        }
        long end = System.currentTimeMillis();
        System.out.println("累加:"+num2);
        System.out.println("synchronized锁:"+ (end-start));
    }
    public static void lock(int i){
        lock.lock();
        num1 ++;
        lock.unlock();
    }
    public static synchronized void sync(int i){
        num2 ++;
    }
}

500,000 ++ Test Data:

累加:500000
ReentrantLock锁:20
累加:500000
synchronized锁:28

Speak with the data, it is clear that under high concurrency, performance is better than ReentrantLock synchronized, although the gap is only a few milliseconds, of course, here I do not use contrast CPU.

100,000 ++ Test Data:

累加:100000
ReentrantLock锁:13
累加:100000
synchronized锁:8

analysis

At this time a small partner may ask, is there a precise threshold, to distinguish between the use of these two locks? Of course, before answering this question, first look at the similarities and differences between these two locks in the end.

Lock implementation

Synchronized is dependent on the JVM implementation, the performance of the original grammar level students mutex. Developers can not see directly related to the source code, but we can see the class file information generated through the use of tools to analyze javap achieve the Synchronize. Sync block is used monitorenter and monitorexit instructions for implementing the synchronization method relies on the process modifiers ACC_SYNCHRONIZED implemented.

ReenTrantLock is based on the JDK implementation, and performance of a mutex API level, through access to the source code developers can understand.

Reentrancy

ReenTrantLock literally means re-entering the locks, lock the synchronized keyword is used reentrant, about the difference between the two is unlikely.

Functional differences

Synchronized more convenient to use, does not require developers to manually lock and release the lock, and the need to manually ReenTrantLock declaration lock and release locks (Lock () and unlock () method with the try / finally statement block implemented)

ReenTrantLock and flexibility in fine-grained locks superior to Synchronized. In addition, it has added some advanced features, mainly in the following three: interruptible wait, can achieve a fair locks and lock can bind multiple conditions.

Development History

About synchronized with ReentrantLock

After after JDK 1.6, virtual machine optimized for the synchronized keyword as a whole, in terms of performance and synchronized ReentrantLock has no obvious gap, so in the use of options, depending on the scene may be, in most cases we still recommend that the synchronized keyword one reason is easy to use semantic clarity, the second is the performance of the virtual machine is automatically optimized for us. The ReentrantLock provides a variety of synchronization features, such as time-out to acquire the lock can be interrupted acquire the lock (synchronized synchronization is not interrupted), wait for multiple condition variables wake-up mechanism (Condition), etc., so when we do need to use these functions may be chosen ReentrantLock

Guess you like

Origin blog.51cto.com/14230003/2443061