Skip to content
javahacks.dev
Concurrency

How to Use ReentrantLock and Condition Variables in Java

Use ReentrantLock for timed and interruptible locking and Condition for waiting on state, with a bounded buffer example and the unlock-in-finally rule.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, Linux, IntelliJ IDEA and Apache Maven logos.

synchronized is the simplest way to protect shared state in Java and it covers most needs. ReentrantLock is the same idea made explicit: you acquire and release the lock yourself, and in exchange you get abilities the keyword lacks. You can try to take the lock without waiting, give up after a timeout, respond to interruption while waiting, ask for fair ordering, and create several Condition objects on one lock. This post shows the pattern, then the conditions that replace wait and notify, and says when the keyword remains the better choice. It uses Java 25.

The pattern

java
class Counter {

    private final ReentrantLock lock = new ReentrantLock();
    private long value;

    void increment() {
        lock.lock();
        try {
            value++;
        } finally {
            lock.unlock();
        }
    }

    long get() {
        lock.lock();
        try {
            return value;
        } finally {
            lock.unlock();
        }
    }
}

The shape never changes: lock, then try, then the work, then unlock in finally. The finally is not optional. Unlike synchronized, which releases the monitor automatically when the block exits, a lock stays held if an exception skips the unlock, and every other thread then blocks forever. Put lock() before the try, not inside it, so that a failure to acquire does not run the finally and unlock a lock you never held. The lock is reentrant: a thread that holds it can acquire it again, with a count, and must unlock the same number of times.

tryLock avoids waiting forever

java
boolean transfer(Account from, Account to, long amount) throws InterruptedException {
    if (from.lock.tryLock(50, TimeUnit.MILLISECONDS)) {
        try {
            if (to.lock.tryLock(50, TimeUnit.MILLISECONDS)) {
                try {
                    from.debit(amount);
                    to.credit(amount);
                    return true;
                } finally {
                    to.lock.unlock();
                }
            }
        } finally {
            from.lock.unlock();
        }
    }
    return false;       // could not get both locks in time
}

With synchronized, a thread that cannot get the monitor waits without limit, and two threads taking two locks in opposite order deadlock for good. tryLock with a timeout turns that into a failure you can handle, by retrying or reporting. It does not remove the need to order locks consistently, which is the real cure, but it makes a deadlock recoverable and visible. How to recognise and read one is in deadlocks and thread dumps. A variant, lockInterruptibly(), lets another thread cancel a waiting one with interrupt(), which synchronized cannot do.

Condition: wait for a state

A condition lets a thread wait until some state becomes true and be woken when it does. A bounded buffer is the standard example:

java
class BoundedBuffer<T> {

    private final Object[] items = new Object[10];
    private int head, tail, count;

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    void put(T item) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                notFull.await();
            }
            items[tail] = item;
            tail = (tail + 1) % items.length;
            count++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

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

await() releases the lock and parks the thread, then reacquires the lock before returning. signal() wakes one waiter on that condition. The advantage over wait and notify is visible here: there are two wait sets, one for threads waiting for space and one for threads waiting for items. A producer signals only consumers. With the keyword, there is one wait set per object, so notifyAll wakes everyone and most of them go back to sleep. In production code you would use ArrayBlockingQueue, which is this, written carefully; see BlockingQueue. The example exists to show the mechanism.

The while loop is not optional

Always test the condition in a while loop, never an if. A waiting thread can wake without having been signalled, which the specification calls a spurious wakeup. It can also wake correctly and find that another thread has already taken the item. With if (count == 0) notEmpty.await(); the thread proceeds on a false assumption and reads an empty buffer. The loop rechecks the state each time it wakes, so correctness does not depend on who woke it or why. This is the most common bug in hand-written condition code, and it passes every test that does not have contention.

Fairness

new ReentrantLock(true) grants the lock to the longest-waiting thread. The default, unfair mode lets a thread that arrives at the right moment take the lock ahead of the queue, which gives higher throughput and can starve a waiting thread. Fair locks prevent starvation and are measurably slower under contention. Use the fair mode only when you have seen starvation, not by default. Note that tryLock() without arguments ignores fairness, and can barge in even on a fair lock.

Observing a lock

The lock exposes state for diagnostics: isLocked(), isHeldByCurrentThread(), getHoldCount() and getQueueLength(). Use them in assertions and logging, never to make decisions, since the answer can change before you act on it. A thread dump shows which thread owns a ReentrantLock as well as which are waiting, in the section on locked ownable synchronizers, which makes these locks easier to debug than monitors. With virtual threads on Java 25, ReentrantLock parks cooperatively, and so does synchronized since JDK 24, as explained in pinning.

Common mistakes

Four mistakes account for most lock bugs in reviews. The first is locking outside the try, or unlocking outside a finally, which leaves the lock held after an exception. The second is signalling without holding the lock: signal() and await() must be called by the thread that owns the lock, or they throw IllegalMonitorStateException. The third is holding a lock while calling code you do not control, such as a listener or a callback, because that code may take other locks in a different order and produce a deadlock. Do the work under the lock, release it, then call out. The fourth is using the same lock for unrelated state. One lock guarding two independent fields makes threads wait for each other for no reason; give each field its own lock when they are independent, and measure before splitting further, since more locks bring more ordering rules.

A fifth, subtler one is forgetting that await can throw InterruptedException. Handle it by restoring the flag and returning, or by propagating it, never by swallowing it. A thread that ignores interruption cannot be stopped by an executor shutdown, and the service hangs at exit.

Testing lock-based code

A test that runs the code once proves little. Run it from several threads many times and check an invariant at the end. For the counter above, start 16 threads that each increment 100,000 times and assert the total is 1,600,000. Remove the lock and the test fails, which shows it measures what you think. For the buffer, run producers and consumers and assert that every item put in comes out exactly once. Bound each test with a timeout so a deadlock fails fast instead of hanging the build; the JUnit annotations are in timeouts, and stress libraries such as jcstress go further when the code is subtle.

When to prefer something else

Use synchronized when you need none of the extras. It is shorter, cannot be left locked, and the JVM optimises it well. Use a read-write lock or StampedLock when reads dominate, covered in read-write locks. Use an atomic variable for a single counter or flag, a concurrent collection for shared maps and queues, and a higher-level tool such as a Semaphore or CountDownLatch when the need is to limit or coordinate threads and not to protect data. The comparison with the keyword is in synchronized blocks and monitors. The contracts are in the [ReentrantLock Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/locks/ReentrantLock.html) and the [Condition Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/locks/Condition.html).

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.