Difference: 1. Lock is an interface, and synchronized is a keyword of java. 2. Synchronized will automatically release the lock it holds when an exception occurs, so deadlock will not occur; when an exception occurs, synchronized will not actively release the lock it holds, and the lock must be released manually, which may cause deadlock.
#In distributed development, locks are an important way to control threads. Java also provides two lock mechanisms for this purpose, synchronized and lock.
0. Synchronized implementation principle
Every object in Java can be used as a lock, which is the basis for synchronized to achieve synchronization:
Ordinary synchronization method, the lock is the current instance object
Static synchronization method, the lock is the class object of the current class
Synchronization method block , the lock is the object in the brackets
When a thread accesses a synchronized code block, it first needs to obtain the lock. When it exits or throws an exception, it must release the lock. So how does it implement this mechanism? Let’s look at a simple piece of code first:
package cn.alibab.javap;public class SynchronizedTest { public synchronized void test1(){ } public void test2(){ synchronized (this){ } } }
Use the javap tool (javap is a decomposer of class files after java compilation) to view the generated class file information to analyze the implementation of Synchronized
As can be seen from the above, the synchronization code block is implemented using the monitorenter and monitorexit instructions. The synchronization method (not visible here needs to look at the underlying implementation of the JVM ) relies on the ACC_SYNCHRONIZED implementation on the method modifier.
Synchronized code block: The monitorenter instruction is inserted into the beginning of the synchronized code block after compilation, and the monitorexit instruction is inserted into the end of the synchronized code block. The JVM needs to ensure that each monitorenter has A monitorexit corresponds to it. Any object has a monitor associated with it. When a monitor is held, it will be in a locked state. When the thread executes the monitorenter instruction, it will try to obtain the monitor ownership corresponding to the object, that is, try to obtain the lock of the object; [Excerpted from the Art of Concurrent Programming]
Synchronized method: The synchronized method will It is translated into ordinary method call and return instructions such as: invokevirtual and areturn instructions. There are no special instructions at the VM bytecode level to implement the method modified by synchronized. Instead, the method is added to the method table of the Class file. The synchronized flag position in the access_flags field is 1, indicating that the method is a synchronized method and uses the object that calls the method or the Class to which the method belongs to represent the Klass in the JVM's internal object as the lock object. (Excerpted from: http://www.cnblogs.com/javaminer/p/3889023.html)
The difference between synchronized and lock
The difference is as follows:
Source:
lock is an interface, and synchronized is a keyword of java, synchronized is a built-in language implementation;
Whether to release the lock due to exception:
synchronized will automatically release the lock it holds when an exception occurs, so there will be no deadlock; when an exception occurs in lock, it will not actively release the lock it holds, and you must manually unlock to release the lock. , which may cause deadlock to occur. (So it is best to wrap the synchronization code block with try catch and write unlock in finally to avoid the occurrence of deadlock.)
Whether to respond to interrupt
lock is waiting for the lock You can use interrupt to interrupt waiting, but synchronized can only wait for the lock to be released and cannot respond to interrupts;
Do you know whether to acquire the lock
Lock can use trylock to know whether the lock has been acquired. Synchronized cannot;
Lock can improve the efficiency of read operations by multiple threads. (Read and write separation can be achieved through readwritelock)
In terms of performance, if the competition for resources is not fierce, the performance of the two is almost the same, and when the competition for resources is very fierce (that is, there is A large number of threads compete at the same time), at this time the performance of Lock is far better than synchronized. Therefore, it should be selected according to the appropriate situation when using it.
synchronized uses the wait, notify, and notifyAll scheduling mechanisms of the Object object itself, while Lock can use Condition to schedule between threads,
//Condition定义了等待/通知两种类型的方法 Lock lock=new ReentrantLock(); Condition condition=lock.newCondition();...condition.await();...condition.signal(); condition.signalAll();
1. The usage difference between synchronized and lock
synchronized: Add this control to the object that needs to be synchronized. Synchronized can be added to the method or to a specific code block, brackets Indicates the object that needs to be locked.
lock: Generally, the ReentrantLock class is used as the lock. The locking and unlocking locations need to be displayed through lock() and unlock(). Therefore, unlock() is generally written in the finally block to prevent deadlock.
2. The performance difference between synchronized and lock
synchronized is hosted for JVM execution,
and lock is the code written in java to control the lock.
In Java1.5, synchronize is performance inefficient. Because this is a heavyweight operation that requires calling the operation interface, locking may consume more system time than operations other than locking. In contrast, using the Lock object provided by Java has higher performance.
But with Java1.6, changes have taken place. Synchronize is very clear in semantics and can perform many optimizations, including adaptive spin, lock elimination, lock coarsening, lightweight locks, biased locks, etc. As a result, the performance of synchronize on Java1.6 is no worse than Lock. Officials also stated that they also support synchronize more and there is room for optimization in future versions.
The specific differences between the two mechanisms:
synchronized originally used the CPU pessimistic locking mechanism, that is, the thread obtains an exclusive lock. Exclusive lock means that other threads can only rely on blocking to wait for the thread to release the lock. When the CPU conversion thread is blocked, it will cause thread context switching. When there are many threads competing for the lock, it will cause frequent context switching of the CPU, resulting in very low efficiency.
Lock uses optimistic locking. The so-called optimistic locking is to complete an operation without locking each time but assuming that there is no conflict. If it fails due to a conflict, it will be retried until it succeeds. The mechanism implemented by optimistic locking is CAS operation (Compare and Swap). We can further study the source code of ReentrantLock and find that one of the more important methods of obtaining the lock is compareAndSetState. This is actually the special instruction provided by the called CPU.
Modern CPUs provide instructions that can automatically update shared data and detect interference from other threads, and compareAndSet() uses these instead of locks. This algorithm is called a non-blocking algorithm, which means that the failure or suspension of one thread should not affect the failure or suspension of other threads.
3. The difference between synchronized and lock usage
There is no difference between synchronized primitive and ReentrantLock under normal circumstances, but in very complex synchronization applications, please consider using ReentrantLock, especially when encountering the following two requirements.
1. A thread needs to be interrupted while waiting for control of a lock
2. Some wait-notify needs to be processed separately. The Condition application in ReentrantLock can control which thread to notify
3. With fair lock function, each incoming thread will queue up to wait.
Let’s talk about it in detail...
Let’s talk about the first case first. There are two lock mechanisms of ReentrantLock. , ignore interrupt locks and respond to interrupt locks, which gives us a lot of flexibility. For example: If two threads A and B compete for a lock, thread A obtains the lock and thread B waits. However, thread A really has too many things to deal with at this time and does not return. Thread B may not be able to wait any longer. I want to interrupt myself, stop waiting for this lock, and turn to other things. At this time ReentrantLock provides 2 mechanisms: interruptible/non-interruptible
First, the B thread interrupts itself (or other threads interrupt it), but ReentrantLock does not respond and continues to let the B thread Wait, no matter how you interrupt, I will ignore it (this is the synchronized primitive);
Second, the B thread interrupts itself (or other threads interrupt it), ReentrantLock handles the interrupt, and no longer waits for the lock Come, give up completely.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of What is the difference between synchronized and Lock?. For more information, please follow other related articles on the PHP Chinese website!