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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
