ReentrantLock, Condition and ReadWriteLock

synchronized covers most locking needs, but java.util.concurrent.locks adds what it cannot do: give up after a timeout, stop waiting when interrupted, wait on several separate conditions, and let many readers in at once. This page explains how these locks work underneath, then escapes a real deadlock with tryLock, builds a bounded buffer with two Conditions, measures fairness, and shows the read-write lock's upgrade trap.

Contents

How explicit locks work

Every Java object has a built-in monitor that synchronized locks and unlocks. It is simple and safe, because the lock is released automatically when the block ends, but it can do only one thing: wait until the lock is free. The java.util.concurrent.locks package (Java 5) adds lock objects with a richer API.

ReentrantLock is built on AbstractQueuedSynchronizer (AQS). AQS keeps an int state, here the hold count, the thread that owns the lock, and a queue of waiting threads. The lock() method tries a compare-and-set of the state from 0 to 1; if that fails, the thread joins the queue and parks with LockSupport.park. The unlock() method decrements the state and, at 0, unparks the first waiter. "Reentrant" means the owner can lock again without blocking; the hold count goes up and must come down to 0 with the same number of unlocks.

A Condition is a second queue attached to a lock, playing the role of wait and notify. await() releases the lock and parks; signal() moves one waiter back to the lock's queue. One lock can have several conditions, so producers and consumers can wait in separate queues.

synchronized compared with the explicit locks
CapabilitysynchronizedReentrantLockReentrantReadWriteLock
SinceJava 1.0Java 5Java 5
Released automaticallyYes, at the end of the blockNo: unlock() in finallyNo: unlock() in finally
Try, or give up after a timeoutNotryLock(), tryLock(time, unit)Yes, on each lock
Stop waiting when interruptedNolockInterruptibly()Yes
Wait queues per lockOne (wait, notify)Any number of ConditionsConditions on the write lock
Fair ordering optionNoYesYes
Concurrent readersNoNoYes
Best forMost codeTimeouts, interruptible waits, several conditionsRead-mostly data with long reads

The memory effects are the same as for synchronized: an unlock() happens-before every later lock() of the same lock, so data written under the lock is visible to the next holder. For the optimistic StampedLock, see its own page. All lock examples below ran on JDK 21.

ReentrantLock basics

An account guarded by a ReentrantLock shows the standard pattern, reentrancy and the timed and interruptible ways to wait. Another thread holds the lock during the timed and interruptible cases, so those paths really have to wait.

Java
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LockBasics {

    private final ReentrantLock lock = new ReentrantLock();
    private long balance = 100;

    boolean withdraw(long amount) {
        lock.lock();
        try {                                     // unlock in finally, always
            if (amount > balance) {
                return false;
            }
            balance -= amount;
            return true;
        } finally {
            lock.unlock();
        }
    }

    void transferAll(LockBasics other) {
        lock.lock();
        try {
            other.deposit(balance);               // a different object's lock
            balance = 0;
        } finally {
            lock.unlock();
        }
    }

    void deposit(long amount) {
        lock.lock();
        try {
            balance += amount;
            // Reentrant: the same thread may lock again; the hold count goes up
            lock.lock();
            try {
                System.out.println("  hold count inside nested lock: " + lock.getHoldCount());
            } finally {
                lock.unlock();
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockBasics a = new LockBasics();
        LockBasics b = new LockBasics();
        System.out.println("withdraw 30: " + a.withdraw(30));
        System.out.println("withdraw 500: " + a.withdraw(500));
        a.transferAll(b);
        System.out.println("a=" + a.balance + " b=" + b.balance);

        // tryLock with a timeout: give up instead of waiting forever
        Thread holder = new Thread(() -> {
            a.lock.lock();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                a.lock.unlock();
            }
        });
        holder.start();
        Thread.sleep(50);
        boolean got = a.lock.tryLock(100, TimeUnit.MILLISECONDS);
        System.out.println("tryLock(100 ms) while another thread holds it: " + got
                + ", queued threads: " + a.lock.getQueueLength());
        holder.join();
        System.out.println("tryLock() after release: " + a.lock.tryLock());
        a.lock.unlock();

        // lockInterruptibly: a waiting thread can be told to give up
        a.lock.lock();                            // main holds it now
        Thread waiter = new Thread(() -> {
            try {
                a.lock.lockInterruptibly();
                a.lock.unlock();
            } catch (InterruptedException e) {
                System.out.println("waiter interrupted while waiting for the lock");
            }
        });
        waiter.start();
        Thread.sleep(100);
        System.out.println("hasQueuedThreads: " + a.lock.hasQueuedThreads()
                + ", waiter state " + waiter.getState());
        waiter.interrupt();
        waiter.join();
        a.lock.unlock();

        // unlock() by a thread that does not hold the lock fails loudly
        try {
            a.lock.unlock();
        } catch (IllegalMonitorStateException e) {
            System.out.println("unlock without holding it: IllegalMonitorStateException");
        }
    }
}

Output:

Output
withdraw 30: true
withdraw 500: false
  hold count inside nested lock: 2
a=0 b=170
tryLock(100 ms) while another thread holds it: false, queued threads: 0
tryLock() after release: true
hasQueuedThreads: true, waiter state WAITING
waiter interrupted while waiting for the lock
unlock without holding it: IllegalMonitorStateException
  • The pattern is lock(), then try, then unlock() in finally. With lock() outside the try, a failure to lock never reaches unlock, and an exception inside the guarded code can never leave the lock held forever.
  • Inside deposit, the same thread locked twice and the hold count was 2. A non-reentrant lock would have deadlocked on itself there.
  • tryLock(100, MILLISECONDS) returned false while the holder thread kept the lock, so the caller can report "busy" instead of blocking. After the holder finished, the untimed tryLock() succeeded at once.
  • The waiter in lockInterruptibly() was in state WAITING, not BLOCKED as with synchronized, and it gave up when interrupted. A thread waiting to enter a synchronized block cannot be interrupted.
  • Calling unlock() from a thread that does not hold the lock throws IllegalMonitorStateException. Unlike a semaphore, a lock has an owner.

Escaping a deadlock with tryLock

A transfer locks the source account, then the target. Two transfers in opposite directions at the same time each take their first lock and then wait forever for the other's. The program runs that pair with synchronized, asks the JVM to find deadlocked threads, and then runs the same pair with tryLock and a random back-off.

Java
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Deadlock {

    static class Account {
        final String name;
        final Object monitor = new Object();
        final ReentrantLock lock = new ReentrantLock();
        long balance = 1000;

        Account(String name) {
            this.name = name;
        }
    }

    // Locks "from" then "to": two opposite transfers lock in opposite orders
    static void transferSync(Account from, Account to, long amount) {
        synchronized (from.monitor) {
            sleep(50);                                    // widen the window
            synchronized (to.monitor) {
                from.balance -= amount;
                to.balance += amount;
            }
        }
    }

    // Same order problem, but tryLock gives up, backs off and retries
    static int transferTryLock(Account from, Account to, long amount)
            throws InterruptedException {
        int attempts = 0;
        while (true) {
            attempts++;
            if (from.lock.tryLock(10, TimeUnit.MILLISECONDS)) {
                try {
                    sleep(50);
                    if (to.lock.tryLock(10, TimeUnit.MILLISECONDS)) {
                        try {
                            from.balance -= amount;
                            to.balance += amount;
                            return attempts;
                        } finally {
                            to.lock.unlock();
                        }
                    }
                } finally {
                    from.lock.unlock();
                }
            }
            Thread.sleep(ThreadLocalRandom.current().nextInt(1, 30));   // random back-off
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account("A");
        Account b = new Account("B");

        // 1. synchronized: A->B and B->A at the same time
        Thread t1 = Thread.ofPlatform().daemon().start(() -> transferSync(a, b, 100));
        Thread t2 = Thread.ofPlatform().daemon().start(() -> transferSync(b, a, 200));
        t1.join(1000);
        t2.join(1000);
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();
        long[] stuck = mx.findDeadlockedThreads();
        System.out.println("synchronized: both finished? " + !(t1.isAlive() || t2.isAlive())
                + ", deadlocked threads found by ThreadMXBean: "
                + (stuck == null ? 0 : stuck.length));

        // 2. tryLock with back-off: the same two transfers complete
        Account c = new Account("C");
        Account d = new Account("D");
        int[] attempts = new int[2];
        Thread t3 = new Thread(() -> attempts[0] = call(() -> transferTryLock(c, d, 100)));
        Thread t4 = new Thread(() -> attempts[1] = call(() -> transferTryLock(d, c, 200)));
        t3.start();
        t4.start();
        t3.join();
        t4.join();
        System.out.println("tryLock: both finished, C=" + c.balance + " D=" + d.balance
                + ", total still " + (c.balance + d.balance)
                + ", needed retries: " + (attempts[0] + attempts[1] > 2));
    }

    interface Transfer {
        int run() throws InterruptedException;
    }

    static int call(Transfer t) {
        try {
            return t.run();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return -1;
        }
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
synchronized: both finished? false, deadlocked threads found by ThreadMXBean: 2
tryLock: both finished, C=1100 D=900, total still 2000, needed retries: true
  • With synchronized, neither transfer finished, and ThreadMXBean.findDeadlockedThreads() reported 2 deadlocked threads. Nothing can break this: the threads cannot be interrupted out of the lock and will wait until the JVM exits. They were daemon threads, which is the only reason this program ends. A thread dump (jstack, or jcmd PID Thread.print) reports the same deadlock.
  • With tryLock, a transfer that cannot get its second lock releases its first one, sleeps a random 1 to 29 ms and starts again. Both transfers completed: C went from 1,000 to 1,100 and D to 900, and the total stayed 2,000. At least one transfer needed a retry. The random back-off matters; with a fixed delay, the two threads can keep colliding in step.
  • The simpler and usually better fix is a global lock order: always lock the account with the smaller id first. Then opposite transfers lock in the same order and cannot deadlock. tryLock is the tool when no such order exists.

Conditions: a bounded buffer

A bounded buffer is the textbook use of conditions: producers must wait while it is full and consumers while it is empty. With wait and notifyAll both kinds of thread share one queue; with two conditions each waits in its own. Two producers each send the numbers 1 to 10,000 through a buffer of 4 to two consumers, so the sum taken must be 2 × 50,005,000.

Java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBuffer<T> {

    private final Object[] items;
    private int putIndex;
    private int takeIndex;
    private int count;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();   // producers wait here
    private final Condition notEmpty = lock.newCondition();  // consumers wait here
    final AtomicInteger producerWaits = new AtomicInteger();
    final AtomicInteger consumerWaits = new AtomicInteger();

    BoundedBuffer(int capacity) {
        items = new Object[capacity];
    }

    void put(T item) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {          // while, not if: re-check after waking
                producerWaits.incrementAndGet();
                notFull.await();                     // releases the lock while waiting
            }
            items[putIndex] = item;
            putIndex = (putIndex + 1) % items.length;
            count++;
            notEmpty.signal();                       // wake one consumer, not producers
        } finally {
            lock.unlock();
        }
    }

    @SuppressWarnings("unchecked")
    T take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                consumerWaits.incrementAndGet();
                notEmpty.await();
            }
            T item = (T) items[takeIndex];
            items[takeIndex] = null;
            takeIndex = (takeIndex + 1) % items.length;
            count--;
            notFull.signal();                        // wake one producer
            return item;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BoundedBuffer<Integer> buffer = new BoundedBuffer<>(4);
        int perProducer = 10000;
        long[] consumed = new long[2];
        Thread[] threads = new Thread[4];
        for (int p = 0; p < 2; p++) {
            threads[p] = new Thread(() -> {
                try {
                    for (int i = 1; i <= perProducer; i++) {
                        buffer.put(i);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        for (int c = 0; c < 2; c++) {
            int me = c;
            threads[2 + c] = new Thread(() -> {
                try {
                    for (int i = 0; i < perProducer; i++) {
                        consumed[me] += buffer.take();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        long expected = 2L * perProducer * (perProducer + 1) / 2;
        System.out.println("2 producers x 10,000 items through a buffer of 4");
        System.out.println("sum taken: " + (consumed[0] + consumed[1]) + ", expected " + expected);
        System.out.println("producers had to wait: " + (buffer.producerWaits.get() > 0)
                + ", consumers had to wait: " + (buffer.consumerWaits.get() > 0));
        System.out.println("left in buffer: " + buffer.count);
    }
}

Output:

Output
2 producers x 10,000 items through a buffer of 4
sum taken: 100010000, expected 100010000
producers had to wait: true, consumers had to wait: true
left in buffer: 0
  • The sum matched, 100,010,000, and the buffer ended empty. Both producers and consumers had to wait at times, so both conditions were really used. How many waits happen changes from run to run.
  • await() sits in a while loop, not an if. A woken thread must check the condition again, because another thread may have taken the slot first, and because await may return spuriously, which the Condition Javadoc explicitly allows.
  • put signals notEmpty and take signals notFull, so a producer only ever wakes a consumer and vice versa. With a single wait queue, notify could wake another producer that finds the buffer still full; that is why code with wait usually needs notifyAll, which wakes everyone.
  • This is essentially how ArrayBlockingQueue is implemented. In application code, use the BlockingQueue classes rather than writing your own.

Fair locks and what fairness costs

new ReentrantLock(true) creates a fair lock that grants the lock to the longest-waiting thread. The default, non-fair lock lets a thread that arrives just as the lock is released take it immediately, ahead of the queue. Four threads each lock and unlock a million times; the counter check proves both locks gave exclusive access.

Java
import java.util.concurrent.locks.ReentrantLock;

public class Fairness {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("4 threads, 1,000,000 lock/unlock each, best of 3");
        for (boolean fair : new boolean[] {false, true}) {
            long best = Long.MAX_VALUE;
            for (int run = 0; run < 3; run++) {
                ReentrantLock lock = new ReentrantLock(fair);
                long[] counter = new long[1];
                Thread[] ts = new Thread[4];
                long t0 = System.nanoTime();
                for (int i = 0; i < 4; i++) {
                    ts[i] = new Thread(() -> {
                        for (int k = 0; k < 1000000; k++) {
                            lock.lock();
                            try {
                                counter[0]++;
                            } finally {
                                lock.unlock();
                            }
                        }
                    });
                    ts[i].start();
                }
                for (Thread t : ts) {
                    t.join();
                }
                best = Math.min(best, System.nanoTime() - t0);
                if (counter[0] != 4000000) {
                    throw new AssertionError(counter[0]);
                }
            }
            System.out.printf("fair=%-5s %,6d ms, counter exact%n", fair, best / 1000000);
        }
    }
}

Output (2-CPU Linux machine, JDK 21; best of 3, a rough comparison):

Output
4 threads, 1,000,000 lock/unlock each, best of 3
fair=false     71 ms, counter exact
fair=true     889 ms, counter exact
  • The fair lock was clearly slower: between two and about twelve times slower than the non-fair lock in repeated runs of this program, and single runs were sometimes far slower still. A fair unlock must hand the lock to a parked thread, which has to be woken and scheduled, while the lock sits unused.
  • The non-fair lock lets a running thread barge in and take the lock in a few nanoseconds. That favours throughput, at the risk of one thread waiting much longer than others.
  • Use a fair lock when long waits are unacceptable, for example when some threads would otherwise starve. Note that the untimed tryLock() barges even on a fair lock; tryLock(0, unit) respects fairness.

ReadWriteLock: many readers, one writer

A ReentrantReadWriteLock is a pair of locks: any number of threads can hold the read lock together, while the write lock is exclusive. The program has four threads read a configuration map at once, each read taking 50 ms, then tries the two ways of moving between the locks.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWrite {

    private final Map<String, String> config = new HashMap<>(Map.of("mode", "fast"));
    private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private final AtomicInteger readersInside = new AtomicInteger();
    private final AtomicInteger maxReaders = new AtomicInteger();

    String read(String key) throws InterruptedException {
        rw.readLock().lock();                    // many readers may hold this together
        try {
            maxReaders.accumulateAndGet(readersInside.incrementAndGet(), Math::max);
            Thread.sleep(50);
            readersInside.decrementAndGet();
            return config.get(key);
        } finally {
            rw.readLock().unlock();
        }
    }

    void write(String key, String value) {
        rw.writeLock().lock();                   // exclusive: no readers, no other writers
        try {
            config.put(key, value);
        } finally {
            rw.writeLock().unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadWrite cache = new ReadWrite();
        ExecutorService pool = Executors.newFixedThreadPool(4);
        long start = System.nanoTime();
        for (int i = 0; i < 4; i++) {
            pool.submit(() -> cache.read("mode"));
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        long ms = (System.nanoTime() - start) / 1000000;
        System.out.println("4 reads of 50 ms took under 100 ms: " + (ms < 100)
                + "; max readers at once: " + cache.maxReaders.get());
        cache.write("mode", "safe");
        System.out.println("after write: " + cache.config);

        // Upgrading is not supported: a read lock holder cannot get the write lock
        cache.rw.readLock().lock();
        try {
            System.out.println("write lock while holding read lock: "
                    + cache.rw.writeLock().tryLock(200, TimeUnit.MILLISECONDS)
                    + " (writeLock().lock() would wait forever)");
        } finally {
            cache.rw.readLock().unlock();
        }

        // Downgrading is supported: take the read lock before releasing the write lock
        cache.rw.writeLock().lock();
        cache.config.put("mode", "safe-v2");
        cache.rw.readLock().lock();
        cache.rw.writeLock().unlock();
        try {
            System.out.println("downgraded, reading " + cache.config.get("mode")
                    + ", read holds " + cache.rw.getReadHoldCount());
        } finally {
            cache.rw.readLock().unlock();
        }
    }
}

Output:

Output
4 reads of 50 ms took under 100 ms: true; max readers at once: 4
after write: {mode=safe}
write lock while holding read lock: false (writeLock().lock() would wait forever)
downgraded, reading safe-v2, read holds 1
  • Four reads of 50 ms finished in under 100 ms, with all 4 readers inside at the same time. With a ReentrantLock they would have taken 200 ms, one after another.
  • Upgrading does not work: a thread holding the read lock could not get the write lock, and writeLock().lock() would wait forever for itself to release the read lock. Release the read lock first, take the write lock, and check the data again, because it may have changed in between.
  • Downgrading does work: while holding the write lock, take the read lock, then release the write lock. The thread keeps reading a value no writer can change in between.
  • A read-write lock pays off only when reads are long or contended and writes are rare. For short reads, its extra bookkeeping can make it slower than a plain lock. A ConcurrentHashMap or an immutable map swapped through a volatile field is often simpler; for optimistic reads that take no lock at all, see StampedLock.

Choosing a lock

Which locking tool to use
SituationUse
Ordinary mutual exclusionsynchronized; see synchronized and volatile
Give up after a timeout, or avoid deadlock without a lock orderReentrantLock.tryLock(time, unit)
A waiting thread must be cancellablelockInterruptibly()
Several wait conditions on the same stateOne ReentrantLock with several Conditions
Threads must not starvenew ReentrantLock(true), accepting lower throughput
Long reads, rare writesReentrantReadWriteLock
Very frequent short readsStampedLock optimistic reads, or immutable snapshots
A single counter or referenceAtomic classes, no lock at all

Before Java 24, a virtual thread that blocked inside synchronized pinned its carrier thread, which made ReentrantLock the recommended lock for virtual-thread code; JEP 491 removed that limitation in Java 24. See virtual threads.