Possible Duplicate:
Synchronization vs Lock
I am wondering is there big difference in using ReentrentLock and Synchronized(object)?
Why it is called reentrentLock? to permit recurive call from the same thread?
I am wondering is there big difference in using
ReentrantLock
andsynchronized (object)
.
The main differences are:
With synchronized
the locking / unlocking is tied to the block structure of your source code. A synchronized
lock will be released when you exit the block, no matter how you do this. For instance, it will be released if the block terminates due to an unexpected exception.
With explicit locking this is not the case, so you could acquire a ReentrantLock
(or any other Lock
) in one method and release it in another one. But the flip side is that you must remember to explicitly release the Lock
at the appropriate time / place. If you don't you'll end up with a stuck lock, and (maybe) deadlocks. In short, ReentrantLock
is more complicated and potentially more error prone.
The primitive locking that you get with synchronized
works with Object.wait()
and Object.notify()
. Lock
s don't.
A ReentrantLock
can be created to be "fair", which means that threads that are waiting to acquire a given lock will acquire the lock in fifo order. Primitive locks are not fair.
The ReentrantLock
API has methods that can be used to test whether the lock is in use, find out the length of the lock queue, try to acquire the lock without blocking, and various other things. None of this functionality is available for primitive locks.
Why it is called a reentrant lock? to permit recursive call from the same thread?
A reentrant lock allows a thread that is holding a lock to acquire it again. One of the ways that this could happen is through recursion, but there are others too.
For the record, synchronized
locks are also reentrant, so you don't need to worry about recursion, or other scenarios where a thread might acquire a lock it already holds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With