Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
Why should you prefer ReentrantLock over synchronized in some cases?
ReentrantLock offers capabilities the intrinsic synchronized keyword simply doesn't have.
It supports tryLock() with an optional timeout, so a thread can back off instead of blocking forever; lockInterruptibly(), so a thread waiting for the lock can respond to interruption; a configurable fairness policy that grants the lock roughly in request order rather than allowing barging; and multiple Condition objects per lock, which lets you build wait sets for different conditions instead of being limited to one implicit wait set per monitor.
ReentrantLock lock = new ReentrantLock(); if (lock.tryLock(500, TimeUnit.MILLISECONDS)) { try { /* critical section */ } finally { lock.unlock(); } }
The trade-off is that you're responsible for calling unlock() yourself, always in a finally block, since the JVM won't release it automatically the way it releases a monitor when a synchronized block exits.
More Related questions...