Java core learning path Level 2 This level · 8 of 29
Medium java java-21

What is the difference between synchronized and ReentrantLock?

The 30 second answer

Both give mutual exclusion and the same memory visibility guarantees. Synchronized is simpler and always releases the lock when the block ends, even on an exception. ReentrantLock gives more control: try to lock with a timeout, wait in a way that can be interrupted, optional fairness, and multiple conditions. The cost is that I must unlock in a finally block myself.

Could you say this in an interview?

The same critical section, side by side:

// ReentrantLock: wait at most 500 ms, then back off
private final ReentrantLock lock = new ReentrantLock();

boolean transferWithLock() throws InterruptedException {
    if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
        try {
            // critical section
            return true;
        } finally {
            lock.unlock();               // always release yourself
        }
    }
    return false;                         // lock busy: retry later or fail fast
}

// synchronized: same critical section, but no timeout and no way out
private final Object monitor = new Object();

boolean transferWithSynchronized() {
    synchronized (monitor) {             // waits until the monitor is free
        // critical section
        return true;
    }                                     // released automatically, even on an exception
}
synchronizedReentrantLock
Releaseautomaticmanual, in finally
Try / timeoutnotryLock(), tryLock(timeout)
Interruptible waitnolockInterruptibly()
Fairnessnonew ReentrantLock(true)
Conditionsone wait set (wait / notify)many Conditions (await / signal)

Fair versus unfair lock:

private final ReentrantLock unfair = new ReentrantLock();     // default: unfair
private final ReentrantLock fair   = new ReentrantLock(true); // fair: longest-waiting thread goes next

unfair.isFair() returns false and fair.isFair() returns true. Note that the untimed tryLock() ignores fairness: it takes the lock if it is free at that moment, even when other threads are waiting.

Both are reentrant: the owning thread can acquire the lock again. Both also give the same memory visibility: the Lock Javadoc says a successful lock and unlock have the same memory effects as entering and leaving a synchronized block.

When to prefer each

  • Default to synchronized for simple cases. If the critical section is short, it lives in one method, and you just need mutual exclusion, synchronized is less code and harder to get wrong. The lock is always released when the block ends, even on an exception, because acquire and release are block-structured. JEP 491 gives the same advice for modern Java: use synchronized where practical, since it is more convenient and less error prone.
  • Use ReentrantLock when you need one of its features:
  • tryLock() or tryLock(timeout, unit): give up instead of waiting forever. Use it to back off under contention, fail fast, or avoid a deadlock when you need two locks.
  • lockInterruptibly(): a thread waiting for the lock can be cancelled with interrupt(). A thread waiting to enter a synchronized block cannot.
  • Fairness: new ReentrantLock(true) hands the lock to the longest-waiting thread. The Javadoc warns that fair locks used by many threads may give lower overall throughput, and that the untimed tryLock() ignores the fairness setting.
  • Several condition variables: newCondition() gives separate wait sets, for example notFull and notEmpty in a bounded buffer. With synchronized there is one wait set per monitor, so notifyAll wakes threads waiting for either condition.
  • Locking that is not block-structured: acquire in one method and release in another, or hand-over-hand locking along a list. synchronized cannot do this.
  • The cost of ReentrantLock is that you must call unlock() in a finally block yourself. Forget it on one path and the lock is held forever.

Virtual-thread pinning with both

  • Java 21 to 23, synchronized: a virtual thread that blocks inside a synchronized block or method is pinned to its carrier platform thread, so the carrier cannot run other virtual threads. JEP 444 recommended replacing synchronized with ReentrantLock where it guards frequent, long blocking operations such as I/O. A virtual thread that blocks on a ReentrantLock unmounts and frees its carrier.
  • Java 24 and later: JEP 491 removed pinning for synchronized, so it now behaves like ReentrantLock here. Code already migrated to ReentrantLock does not need to be changed back.
  • Still pinned with either lock: a virtual thread inside a native method or a foreign function call stays pinned, even on Java 24.
  • Neither lock fixes contention. Holding any lock across slow I/O still makes requests take turns on that path, with or without virtual threads. Keep the critical section short.

Alternate interview scenarios

"Your code uses synchronized everywhere and the application is slow. What's wrong?"
Switching to ReentrantLock would not fix it; the problem is contention. If every request goes through the same lock, requests run one at a time on that path, however many cores you have. I confirm it with a few thread dumps: many threads BLOCKED waiting to lock the same monitor. A JFR recording shows the same thing as monitor-enter events with long durations. Then I shrink the critical sections, so I/O and remote calls happen outside the lock. I swap synchronized maps and counters for ConcurrentHashMap, atomics or LongAdder. I make shared objects immutable, or confine state to one thread, so they need no lock at all. Lock splitting, one lock per account instead of one for the bank, also helps. And on Java 21 with virtual threads, blocking inside synchronized pins the carrier thread, which makes it worse until Java 24.

The next three are practice scenarios: common follow-ups an interviewer may ask about this topic, with model answers.

Practice scenario: "Two threads transfer money between the same two accounts in opposite directions, and the app hangs. What happened and how do you fix it?"

This is a deadlock. Thread A holds account 1's lock and waits for account 2, while thread B holds account 2's lock and waits for account 1, so both block forever. A plain synchronized block can never give up, so the fix is to stop the cycle. The standard fix is a global lock order: always lock the account with the smaller ID first, whichever direction the money moves. With ReentrantLock you can also call tryLock(timeout, unit) on both locks; if either fails, release the one you hold, back off briefly and retry. To confirm it in production, take a thread dump and look for threads waiting on each other's locks, or call ThreadMXBean.findDeadlockedThreads(), which reports cycles on both monitors and ReentrantLocks.

Practice scenario: "A consumer thread sometimes waits forever even though there is data in the queue. Why?"

This is usually a lost wakeup or a bad wait check. Typical causes are checking the condition with if instead of while, waiting without first checking shared state (so a signal sent before the consumer started waiting is missed), or changing the state outside the lock. The rules are the same for wait/notify and Condition.await/signal. Keep the condition in shared state guarded by the lock. Change it and signal while holding the lock. Always wait in a loop: while (queue.isEmpty()) notEmpty.await();. The loop also handles spurious wakeups, which the Object.wait Javadoc says can happen. With one monitor, notify() can wake the wrong kind of waiter, so code using synchronized usually needs notifyAll().

Practice scenario: "Implement a bounded buffer for producers and consumers. Would you use synchronized or ReentrantLock?"

Both work. With synchronized, producers and consumers share one wait set, so every change needs notifyAll(), which wakes threads that cannot proceed. With one ReentrantLock and two Conditions, producers wait on notFull and signal notEmpty, and consumers do the reverse, so only the right kind of thread wakes up. This is the example in the Condition Javadoc. In real code I would mention that ArrayBlockingQueue already does exactly this, and reach for it first.

Sources (14)
  1. ReentrantLock Javadocdocs.oracle.com
  2. Lock Javadoc (memory synchronization)docs.oracle.com
  3. JLS 17.1 Synchronizationdocs.oracle.com
  4. JEP 444: Virtual Threadsopenjdk.org
  5. JEP 491: Synchronize Virtual Threads without Pinningopenjdk.org
  6. Condition Javadocdocs.oracle.com
  7. Java Tutorial: Intrinsic Locks and Synchronizationdocs.oracle.com
  8. Object.wait Javadoc (spurious wakeups)docs.oracle.com
  9. ThreadMXBean.findDeadlockedThreads Javadocdocs.oracle.com
  10. Java Tutorial: Deadlockdocs.oracle.com
  11. Java Tutorial: Guarded Blocksdocs.oracle.com
  12. ArrayBlockingQueue Javadocdocs.oracle.com
  13. jcmd (Thread.print and JFR.start), Java 21docs.oracle.com
  14. java.util.concurrent package summary (Java 21)docs.oracle.com
Previous
Next