synchronized versus ReentrantLock
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)synchronized and ReentrantLock both let only one thread at a time into a critical section, both are reentrant, and both make changes visible to the next thread that takes the lock. The difference is in the extras and in who releases the lock.
Feature comparison: tryLock, timeouts, fairness, conditions
The basic guarantees are the same. Mutual exclusion, reentrancy and visibility work the same way for both. A counter protected by either one gives the right answer.
Example 1 · The same counter, written both ways
import java.util.concurrent.locks.ReentrantLock;
class SyncCounter { private int count = 0;
synchronized void add() { count++; }
synchronized int get() { return count; }}
class LockCounter { private final ReentrantLock lock = new ReentrantLock(); private int count = 0;
void add() { lock.lock(); try { count++; } finally { lock.unlock(); } }
int get() { lock.lock(); try { return count; } finally { lock.unlock(); } }}
public class BothWaysDemo { static void runTwice(Runnable add) throws InterruptedException { Runnable work = () -> { for (int i = 0; i < 100_000; i++) { add.run(); } }; Thread t1 = new Thread(work, "worker-1"); Thread t2 = new Thread(work, "worker-2"); t1.start(); t2.start(); t1.join(); t2.join(); }
public static void main(String[] args) throws InterruptedException { SyncCounter s = new SyncCounter(); LockCounter l = new LockCounter(); runTwice(s::add); runTwice(l::add); System.out.println("synchronized counter: " + s.get()); System.out.println("ReentrantLock counter: " + l.get()); }}synchronized counter: 200000 ReentrantLock counter: 200000
What this code does
- Both counters reach exactly 200000: for plain mutual exclusion they are equally correct.
- The
synchronizedversion is about half as long and has nofinallyto forget. - Nothing in this job needs a timeout, fairness or conditions, so
synchronizedis the better choice here.
Example 2 · What only ReentrantLock can do: give up or be cancelled
import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;
public class OnlyLockCanDemo { static final Object monitor = new Object(); static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException { String[] lockResult = new String[1];
Thread syncUser = new Thread(() -> { synchronized (monitor) { System.out.println("sync-user: finally got the monitor"); } }, "sync-user");
Thread lockUser = new Thread(() -> { try { if (lock.tryLock(100, TimeUnit.MILLISECONDS)) { lock.unlock(); lockResult[0] = "got the lock"; } else { lockResult[0] = "gave up after 100 ms"; } } catch (InterruptedException e) { lockResult[0] = "cancelled"; } }, "lock-user");
synchronized (monitor) { lock.lock(); try { syncUser.start(); lockUser.start(); while (syncUser.getState() != Thread.State.BLOCKED) { Thread.sleep(1); // wait until sync-user is stuck } syncUser.interrupt(); // does not stop a BLOCKED thread lockUser.join(); // lock-user gives up by itself System.out.println("sync-user state: " + syncUser.getState()); System.out.println("lock-user: " + lockResult[0]); } finally { lock.unlock(); } } syncUser.join(); }}sync-user state: BLOCKED lock-user: gave up after 100 ms sync-user: finally got the monitor
What this code does
mainholds both the monitor and the lock.lock-userwaits at most 100 ms withtryLockand then moves on with a clear result.sync-userstaysBLOCKEDin front ofsynchronized, even afterinterrupt(). It can only wait untilmainleaves the block.- If a requirement says "time out" or "cancel", that is the signal to use
ReentrantLock.
The differences are extra features that only ReentrantLock has:
- Do not wait, or wait with a limit:
tryLock()andtryLock(time, unit). A thread in front ofsynchronizedalways waits, for as long as it takes. - Cancel the wait:
lockInterruptibly(). A thread blocked onsynchronizedignoresinterrupt(). - Fairness:
new ReentrantLock(true).synchronizedmakes no fairness promise. - Several waiting rooms:
newCondition()many times.synchronizedhas one wait set per object.
Automatic release versus manual unlock
Automatic release is the big advantage of synchronized. The lock is released when the block ends in any way: normally, by return or by an exception. You cannot forget it.
Example 3 · An exception: released automatically versus left locked
import java.util.concurrent.locks.ReentrantLock;
class FeeDesk { private final ReentrantLock lock = new ReentrantLock(); private int collected = 0;
synchronized void collectSync(int amount) { if (amount <= 0) { throw new IllegalArgumentException("bad amount"); } collected += amount; }
void collectLockNoFinally(int amount) { lock.lock(); if (amount <= 0) { throw new IllegalArgumentException("bad amount"); // skips unlock() } collected += amount; lock.unlock(); }
boolean lockHeld() { return lock.isLocked(); }}
public class ReleaseDemo { public static void main(String[] args) throws InterruptedException { FeeDesk desk = new FeeDesk();
Thread t1 = new Thread(() -> desk.collectSync(-1), "sync-clerk"); Thread t2 = new Thread(() -> desk.collectLockNoFinally(-1), "lock-clerk"); t1.setUncaughtExceptionHandler((t, e) -> { }); // keep the output short t2.setUncaughtExceptionHandler((t, e) -> { }); t1.start(); t1.join(); t2.start(); t2.join();
Thread check = new Thread(() -> { synchronized (desk) { System.out.println("Monitor after the exception: free, another thread got it"); } }, "checker"); check.start(); check.join(); System.out.println("ReentrantLock after the exception: held = " + desk.lockHeld()); }}Monitor after the exception: free, another thread got it ReentrantLock after the exception: held = true
What this code does
- Both clerk threads die with an exception inside the critical section. The handlers only hide the stack traces to keep the output short.
- The
synchronizedmethod released the monitor automatically, so the checker thread enterssynchronized (desk)at once. - The
ReentrantLockwithoutfinallyis still held by a thread that no longer exists. Every laterlock()would wait forever.
A ReentrantLock is released only when your code calls unlock(). That is why every use needs the lock, try, finally pattern. One missing finally and the lock stays held forever. synchronized is also tied to a block of code, so it is always released in the same method that took it. A Lock can be taken in one method and released in another; that is flexible, but easy to get wrong.
Which one to choose by default
Start with synchronized. It is shorter, it cannot leak a lock, and thread dumps show clearly which thread owns which monitor. Since Java 6, the JVM has optimised it heavily, so speed is not a reason to switch for ordinary code.
// Plain mutual exclusion: synchronizedsynchronized void addMarks(int m) { total += m; }
// "Give up after 2 seconds": ReentrantLockif (lock.tryLock(2, TimeUnit.SECONDS)) { try { total += m; } finally { lock.unlock(); }} else { System.out.println("Server busy, try again");}Switch to ReentrantLock when the requirement names one of its features: a timeout, a wait that can be cancelled, fairness, or more than one condition. Even then, check first whether a ready-made tool does the whole job, such as ArrayBlockingQueue for producer and consumer.
The common interview answer
The interview answer fits in four points. Say them in this order, then give one example of when you would switch.
- Both give mutual exclusion, reentrancy and the same visibility (happens-before) guarantee.
ReentrantLockaddstryLock, timed and interruptible waits, an optional fair mode and severalConditionobjects.synchronizedreleases the lock automatically;ReentrantLockneedsunlock()infinally, so it is easier to misuse.- Default to
synchronized; useReentrantLockonly when you need one of its features, for example a booking that must time out.
Next step
Check your understanding
11 quick questions