Java / Java 21 Interview Questions
What are the differences between 'synchronized' and ReentrantLock in Java?
synchronized is Java's built-in intrinsic lock mechanism. ReentrantLock (in java.util.concurrent.locks) provides the same mutual-exclusion guarantee but with more capabilities at the cost of more verbose code.
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Lock acquisition | Implicit — enters on block entry | Explicit — must call lock() |
| Unlock | Automatic on block exit | Explicit — must call unlock() in finally |
| Try to acquire | Not possible | tryLock() / tryLock(timeout, unit) |
| Interruptible lock | Not possible | lockInterruptibly() |
| Fairness | Non-fair (JVM decides) | Can be fair (new ReentrantLock(true)) |
| Condition variables | One per monitor (wait/notify) | Multiple Condition objects per lock |
| Virtual thread pinning | Pins virtual thread to carrier | Does NOT pin — preferred for VTs |
// synchronized — simple cases
synchronized (this) {
// critical section
}
// ReentrantLock — more control, required for virtual-thread-safe code
private final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
void produce(T item) throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) notFull.await();
queue.add(item);
notEmpty.signal();
} finally {
lock.unlock(); // always in finally to prevent lock leaks
}
}
// tryLock — non-blocking attempt
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try { /* critical section */ }
finally { lock.unlock(); }
} else {
System.out.println("Could not acquire lock in time");
}The critical Java 21 consideration: synchronized pins a virtual thread to its carrier OS thread for the duration of the synchronized block, preventing the scheduler from parking the virtual thread and assigning the carrier to another task. ReentrantLock does not pin — the virtual thread can still be parked inside a lock. For high-concurrency virtual-thread applications, replacing hot synchronized blocks with ReentrantLock is a meaningful performance improvement.
More Related questions...