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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The main differences are:
With
synchronizedthe locking / unlocking is tied to the block structure of your source code. Asynchronizedlock 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 otherLock) in one method and release it in another one. But the flip side is that you must remember to explicitly release theLockat the appropriate time / place. If you don’t you’ll end up with a stuck lock, and (maybe) deadlocks. In short,ReentrantLockis more complicated and potentially more error prone.The primitive locking that you get with
synchronizedworks withObject.wait()andObject.notify().Locks don’t.A
ReentrantLockcan 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
ReentrantLockAPI 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.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,
synchronizedlocks 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.