Java when writing multi-thread program, in order to ensure thread security, need to synchronize data , often use two kinds of synchronization is synchronized and re-enter lock Reentrantlock.
Similar points:
There are many similarities between these two modes of synchronization, which are both lock-in and synchronous, which means that when a thread obtains an object lock and enters a synchronization block, other threads that access the synchronization block must block waiting outside the synchronization block. The cost of thread blocking and wakeup is high (the operating system needs to switch back and forth between the user state and the kernel state at a high cost, but can be improved by locking optimizations).
Difference:
The biggest difference between the two approaches is that for synchronized, it is the Java language keyword, which is a native syntax-level mutex that needs to be implemented by the JVM.
Reentrantlock It is an API-level mutex provided after JDK 1.5 and requires the lock () and unlock () methods to be completed with the try/finally statement block .
1.Synchronized
Synchronized in the compilation, will be in the synchronization block before and after the formation of Monitorenter and monitorexit this two-byte code instruction. When executing the monitorenter instruction, the first attempt is to acquire an object lock. If the object is not locked, or when the front-thread already has the object lock, the lock calculator plus 1, the corresponding, in the execution of the monitorexit instruction will be the lock calculator minus 1, when the calculator is 0 o'clock, the lock is released. If an object lock fails, the current thread will block until the object lock is freed by another thread.
2.ReentrantLock
Since Reentrantlock is a set of mutexes provided under the Java.util.concurrent package, theReentrantlock class offers some advanced features compared to synchronized, with the following 3 main items:
1. waiting can be interrupted , the thread holding the lock is not released for a long time, the waiting thread can choose to give up waiting , which is equivalent to synchronized to avoid the deadlock situation.
2. Fair lock , when multiple threads wait for the same lock, the lock must be acquired in the order in which the lock is requested , the synchronized lock is not fair, and the Reentrantlock default constructor is the created non-fair lock, A fair lock can be set by the parameter true, but the performance of the fair lock performance is not very good.
3. A lock binds multiple conditions , and a Reentrantlock object can be bound to an object at the same time.
Two synchronization modes of Java, the difference between synchronized and Reentrantlock