Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference in using ReentrentLock and Synchronized(object)? [duplicate]

Tags:

java

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?

like image 427
user496949 Avatar asked Feb 03 '23 09:02

user496949


1 Answers

I am wondering is there big difference in using ReentrantLock and synchronized (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(). Locks 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.

like image 144
Stephen C Avatar answered Feb 12 '23 07:02

Stephen C