“When do we use ReentrantLock in Java?” — perfect for your Java 8 interviews.
✅ When We Use ReentrantLock
You use ReentrantLock instead of synchronized when you need more advanced locking features that synchronized cannot provide.
Below are the key situations:
✅ 1. When You Need to Try Lock Without Waiting
synchronized blocks always wait until the lock is free.
But with ReentrantLock, you can use tryLock():
if (lock.tryLock()) {
try {
// do work
} finally {
lock.unlock();
}
} else {
// handle if lock not available
}
Useful for avoiding deadlocks.
✅ 2. When You Need to Interrupt a Thread Waiting for a Lock
synchronized cannot interrupt a thread waiting for a lock,
but lock.lockInterruptibly() can.
This is needed in high-performance systems like banking, trading, etc.
✅ 3. When You Need Fairness
You can make a lock fair:
Lock lock = new ReentrantLock(true); // fair lock
Fair lock gives access to next waiting thread, not the latest one.
✅ 4. When You Need Multiple Condition Variables
With synchronized, you only get one monitor (wait/notify).
ReentrantLock allows multiple conditions:
Condition condition = lock.newCondition();
This helps in producer-consumer or queue systems.
✅ 5. When You Need Better Performance (Under High Contention)
Under heavy thread loads, ReentrantLock performs better than synchronized.
⭐ One-Liner Interview Answer
We use ReentrantLock when we need advanced locking features like tryLock, fairness, interruptible waits, and multiple conditions—features that synchronized does not support.
π‘ Want code examples?
I can give you:
✔ Producer–Consumer using ReentrantLock
✔ Deadlock-free example using tryLock
✔ Fair vs unfair locks comparison
Just tell me!
No comments:
Post a Comment