Java Concurrency Interview

synchronized, monitors, wait and notify question 31 of 180 mid

What is the difference between synchronized and ReentrantLock in practice?

synchronized is scoped to a block and released by the JVM on any exit path, including an exception. That is a real safety advantage, and it is why it remains the default.

ReentrantLock buys you the things a monitor cannot express: tryLock() to back off instead of blocking, tryLock(timeout) to bound the wait, lockInterruptibly() to stay cancellable, fairness if you need it, several Condition queues per lock, and the ability to lock in one method and unlock in another. The price is that forgetting finally { lock.unlock(); } leaks the lock forever.

On performance, biased locking used to make uncontended synchronized nearly free, but it was disabled in JDK 15 and removed in 18. Measured under contention at 8 threads: synchronized about 18 ops/us, ReentrantLock about 67.

synchronized locks

Quiz yourself on synchronized, monitors, wait and notify Suggest a correction