Compare synchronized, ReentrantLock, ReadWriteLock and StampedLock.
synchronized
- Intrinsic monitor lock on an object; reentrant; released automatically when the block exits, even on exception.
- Simple and well optimised by the JVM (biased locking was removed in JDK 18, but thin/fat locking and lock elision still apply).
- No timeout, not interruptible while waiting, single wait-set (
wait/notify).
ReentrantLock
- Same mutual exclusion semantics, plus:
tryLock()andtryLock(timeout),lockInterruptibly(), optional fairness, and multipleConditions per lock. - Must be released in
finally. - Choose it when you need timeouts (to avoid deadlocks), interruptibility or several condition queues.
ReentrantReadWriteLock
- Many concurrent readers or one writer. Good for read-mostly data with non-trivial read sections.
- Writers can starve under a constant stream of readers in non-fair mode; a reader cannot upgrade to a write lock (deadlock), though a writer can downgrade.
StampedLock (Java 8)
- Adds optimistic reads: read without locking, then
validate(stamp); if a write happened in between, retry with a real read lock. - Very fast for read-heavy workloads, but not reentrant and has no
Conditions, so it is easy to misuse.
Alternatives that avoid locks entirely
Immutable snapshots behind a volatile or AtomicReference, ConcurrentHashMap, LongAdder, and confinement (one thread owns the data).
Example
private final ReentrantLock lock = new ReentrantLock();
boolean transfer(Account from, Account to, BigDecimal amount) throws InterruptedException {
if (!lock.tryLock(200, TimeUnit.MILLISECONDS)) return false; // fail fast instead of hanging
try {
from.debit(amount);
to.credit(amount);
return true;
} finally {
lock.unlock();
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
How do you detect and prevent deadlocks?
Detect: take a thread dump (jstack <pid> or jcmd <pid> Thread.print); the JVM reports "Found one Java-level deadlock" with the threads and locks involved. ThreadMXBean.findDeadlockedThreads() does it programmatically for monitoring. Prevent: acquire locks in a global order (for transfers, lock the account with the smaller id first), use tryLock with timeouts, keep critical sections small, and never call unknown code (callbacks, remote calls) while holding a lock.
What does a fair lock cost?
Fair mode grants the lock in arrival order, preventing starvation, but it disables "barging" (a running thread grabbing a just-released lock), so every hand-off parks and unparks threads. Throughput can drop by an order of magnitude. Use it only when starvation is a real problem.