Skip to lesson

synchronized versus ReentrantLock

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

BothWaysDemo.javaJava
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());    }}
Output
synchronized counter:  200000
ReentrantLock counter: 200000

What this code does

  • Both counters reach exactly 200000: for plain mutual exclusion they are equally correct.
  • The synchronized version is about half as long and has no finally to forget.
  • Nothing in this job needs a timeout, fairness or conditions, so synchronized is the better choice here.

Example 2 · What only ReentrantLock can do: give up or be cancelled

OnlyLockCanDemo.javaJava
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();    }}
Output
sync-user state: BLOCKED
lock-user: gave up after 100 ms
sync-user: finally got the monitor

What this code does

  • main holds both the monitor and the lock. lock-user waits at most 100 ms with tryLock and then moves on with a clear result.
  • sync-user stays BLOCKED in front of synchronized, even after interrupt(). It can only wait until main leaves 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() and tryLock(time, unit). A thread in front of synchronized always waits, for as long as it takes.
  • Cancel the wait: lockInterruptibly(). A thread blocked on synchronized ignores interrupt().
  • Fairness: new ReentrantLock(true). synchronized makes no fairness promise.
  • Several waiting rooms: newCondition() many times. synchronized has 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

ReleaseDemo.javaJava
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());    }}
Output
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 synchronized method released the monitor automatically, so the checker thread enters synchronized (desk) at once.
  • The ReentrantLock without finally is still held by a thread that no longer exists. Every later lock() 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.

Java
// 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.

  1. Both give mutual exclusion, reentrancy and the same visibility (happens-before) guarantee.
  2. ReentrantLock adds tryLock, timed and interruptible waits, an optional fair mode and several Condition objects.
  3. synchronized releases the lock automatically; ReentrantLock needs unlock() in finally, so it is easier to misuse.
  4. Default to synchronized; use ReentrantLock only when you need one of its features, for example a booking that must time out.

Next step

Check your understanding

11 quick questions