Java FAQ: Top Questions
30. What is the difference between ReentrantLock and synchronized?
ReentrantLock
and
synchronized
are Java mechanisms for thread synchronization, but
ReentrantLock
offers more flexibility and features.
-
synchronized:
- Built-in keyword for methods or blocks.
- Automatically releases the lock on block exit.
- Limited control (e.g., no timeout, no fairness).
-
ReentrantLock:
-
Class in
java.util.concurrent.locks
. -
Explicit lock/unlock with
lock()
andunlock()
. - Features: try-lock, timeouts, fairness, and condition variables.
-
Requires manual unlocking, typically in
try-finally
.
-
Class in