Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between synchronized and re-entrant lock? [duplicate]

Tags:

I have used the synchronized keyword and re-entrant locks in Java, but I don't understand how they differ, or which is appropriate for a given situation.

How do I decide when should I use synchronized and when I should use re-entrant locks?

like image 396
noMAD Avatar asked Jan 30 '12 23:01

noMAD


People also ask

What is a reentrant lock?

What Is a Reentrant Lock? A reentrant lock is a mutual exclusion mechanism that allows threads to reenter into a lock on a resource (multiple times) without a deadlock situation. A thread entering into the lock increases the hold count by one every time. Similarly, the hold count decreases when unlock is requested.

What is the difference between ReentrantLock and synchronized?

As stated earlier, the main difference between synchronized and ReentrantLock is the ability to trying to lock interruptibly, and with a timeout. The thread doesn't need to block infinitely, which was the case with synchronized.

What is lock synchronization?

In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive: a mechanism that enforces limits on access to a resource when there are many threads of execution.

Are synchronized methods reentrant?

Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object.


1 Answers

A ReentrantLock is:

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

Extended capabilities include:

  1. The ability to have more than one condition variable per monitor. Monitors that use the synchronized keyword can only have one. This means reentrant locks support more than one wait()/notify() queue.
  2. The ability to make the lock fair. Synchronized blocks are unfair.

    "[fair] locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order."

  3. The ability to check if the lock is being held.
  4. The ability to get the list of threads waiting on the lock.

The disadvantages of reentrant locks are:

  1. Need to add import statement.
  2. Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
  3. The synchronized keyword can be put in method definitions which avoids the need for a block which reduces nesting.

Summary

The synchronized keyword is syntactically nicer, but the Reentrant lock has more features.

like image 146
Jay Avatar answered Sep 27 '22 23:09

Jay