reentrancy
From the name,
ReenTrantLock
literally means a re-entry lock. In fact, the lock used by the
synchronized
keyword is also re-entrant.
There's not much difference between the two about this.
Both are the same thread did not enter once, the counter of the lock is incremented by
1 , so the lock
can not be released
until the counter of the lock drops to
0 .
Implementation of the lock:
Synchronized
is dependent on the
JVM
implementation,
And
ReenTrantLock
is implemented by
JDK
,
What is the difference? To put it bluntly, it is similar to the difference between the operating system to control the implementation and the user's own code implementation.
The implementation of the former is more difficult to see, and the latter has direct source code for reading.
difference in performance
Before
Synchronized
was optimized,
the performance of synchronized was much worse than that of
ReenTrantLock
, but since Synchronized introduced biased locks, lightweight locks (spin locks), the performance of the two is about the same.
In the case where both methods are available, the official even recommends the use of
synchronized
. In fact , the optimization of
synchronized is based on
the CAS technology
in ReenTrantLock .
They all try to solve the locking problem in user mode to avoid blocking threads entering kernel mode.
Functional difference
Convenience: It is obvious that the use of
Synchronized
is more convenient and concise, and the compiler guarantees the lock and release of the lock, while
ReenTrantLock
needs to be manually declared to lock and release the lock. In order to avoid deadlock caused by forgetting to manually release the lock,
So it's better to declare release lock in
fifinally
.