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:
- 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.
- 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."
- The ability to check if the lock is being held.
- The ability to get the list of threads waiting on the lock.
The disadvantages of reentrant locks are:
- Need to add import statement.
- Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
- 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.