Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-26

ReentrantLock and the Lock Interface in Java: tryLock, ReadWriteLock, Condition

The Lock interface from the java.util.concurrent.locks package (added in Java 5) is an explicit lock and an alternative to synchronized. It can do things a monitor can't: try to acquire the lock without waiting or with a timeout (tryLock), wait for it in a way that can be interrupted (lockInterruptibly), hand it to threads in queue order (fair mode), and keep several wait conditions on one lock (Condition). The main implementation is ReentrantLock. Unlike synchronized, you release the lock yourself, so code that uses Lock always follows the same pattern:

private final Lock lock = new ReentrantLock();

public void increment() {
    lock.lock();          // acquire - before try
    try {
        count++;          // critical section
    } finally {
        lock.unlock();    // release - always in finally
    }
}

The pattern isn't a formality. If a thread calls lock() and then dies with an exception before reaching unlock(), it takes the lock with it: the thread is gone, isLocked() still returns true, and every other thread waits forever. synchronized would have released the monitor on its own. The example with its output is in The lock() / try / finally Pattern.

The lock() / try / finally Pattern: Why unlock() Goes in finally

unlock() is called in a finally block because a Lock is never released automatically: if an exception is thrown or an early return fires between lock() and unlock(), the lock stays taken. And lock() goes before try, not inside it: if the acquisition itself fails, finally must not release anything.

Here is what happens when unlock() simply sits at the end of the method:

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

public class ForgottenUnlock {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            lock.lock();
            System.out.println("worker acquired the lock");
            int value = Integer.parseInt("not a number"); // NumberFormatException
            System.out.println(value);
            lock.unlock();                                // never reached
        }, "worker");
        worker.start();
        worker.join();

        System.out.println("worker alive: " + worker.isAlive());
        System.out.println("isLocked: " + lock.isLocked());
        if (lock.tryLock(1, TimeUnit.SECONDS)) {          // lock() would hang here forever
            lock.unlock();
            System.out.println("main acquired the lock");
        } else {
            System.out.println("main gave up after waiting 1 s");
        }
    }
}
worker acquired the lock
Exception in thread "worker" java.lang.NumberFormatException: For input string: "not a number"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	...
worker alive: false
isLocked: true
main gave up after waiting 1 s

The worker thread has finished, yet it still owns the lock, and nobody can release it now: unlock() from another thread throws IllegalMonitorStateException. In this example main uses tryLock with a timeout only so that the program can exit. With a plain lock() it would hang, and a thread dump would show main stuck in WAITING (parking) without a single error in the logs. The fix is the same code in the lock(); try { … } finally { unlock(); } form: the exception still kills the thread, but the lock gets released.

Why not put lock() inside try? lock() itself normally doesn't throw, but lockInterruptibly() throws InterruptedException, and some Lock implementations can throw while acquiring. If the acquisition sits inside try and fails, finally calls unlock() on a lock the thread doesn't hold. You get an IllegalMonitorStateException from finally that replaces the original exception, and the real cause of the failure is lost:

try {
    lock.lockInterruptibly();   // wrong: an interrupt here…
    doWork();
} finally {
    lock.unlock();              // …ends in IllegalMonitorStateException instead of InterruptedException
}

With tryLock() the pattern is slightly different: unlock() is called only in the branch where the lock was actually acquired.

if (lock.tryLock()) {
    try {
        doWork();
    } finally {
        lock.unlock();
    }
} else {
    // the lock is busy - do something else, release nothing
}

Methods of the Lock Interface

The Java Lock interface declares six methods: four ways to acquire the lock (lock, lockInterruptibly, tryLock(), tryLock(time, unit)), unlock to release it, and newCondition to create wait conditions. The acquisition methods differ in what happens when the lock is busy: wait indefinitely, wait but allow interruption, don't wait at all, or wait up to a timeout.

Method If the lock is busy Exceptions and edge cases
void lock() Waits as long as it takes; the thread is WAITING interrupt() doesn't stop the wait: the flag gets set and the thread keeps waiting
void lockInterruptibly() Waits until the lock is free or the thread is interrupted InterruptedException on interrupt, and also if the interrupted flag was already set before the call
boolean tryLock() Doesn't wait: returns false immediately On a ReentrantLock(true) it grabs a free lock ahead of the queue, breaking fairness
boolean tryLock(long time, TimeUnit unit) Waits no longer than the timeout, then returns false; the thread is TIMED_WAITING InterruptedException on interrupt; with time <= 0 it doesn't wait at all; respects fairness
void unlock() — On ReentrantLock decrements the hold count by 1; if the thread doesn't own the lock — IllegalMonitorStateException
Condition newCondition() — Creates a wait condition bound to this lock; on the read lock of ReentrantReadWriteLock — UnsupportedOperationException

Note the state of a waiting thread. A thread waiting for a synchronized monitor is BLOCKED, but a thread waiting in ReentrantLock.lock() is WAITING: the locks in java.util.concurrent.locks are built on LockSupport.park(). The difference between these states is covered in BLOCKED vs WAITING, and the ReentrantLock question specifically in the FAQ of the thread states lesson.

Visibility guarantees are the same as with a monitor: everything a thread wrote before unlock() is visible to the next thread after lock() on the same lock. The Lock Javadoc requires this from every implementation. What happens-before means is explained in volatile in Java.

ReentrantLock: Reentrancy and getHoldCount()

ReentrantLock is a reentrant lock: a thread that already owns it can call lock() again without waiting. The lock counts acquisitions, and to release it the thread has to call unlock() as many times as it called lock(). getHoldCount() returns the current count.

A synchronized monitor works the same way (see The Monitor: How synchronized Works). The difference is that with ReentrantLock you can inspect the state from code:

import java.util.concurrent.locks.ReentrantLock;

public class HoldCountExample {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        lock.lock();
        lock.lock();                                   // reentry by the same thread
        System.out.println("holdCount = " + lock.getHoldCount());
        lock.unlock();
        System.out.println("After one unlock(): holdCount = " + lock.getHoldCount()
                + ", isLocked = " + lock.isLocked());

        Thread other = new Thread(() -> {
            System.out.println("other: isHeldByCurrentThread = " + lock.isHeldByCurrentThread());
            try {
                lock.unlock();                         // someone else's lock
            } catch (IllegalMonitorStateException e) {
                System.out.println("other: unlock() -> " + e.getClass().getSimpleName());
            }
            lock.lock();                               // waits until main releases it
            try {
                System.out.println("other acquired the lock");
            } finally {
                lock.unlock();
            }
        }, "other");
        other.start();
        Thread.sleep(200);                             // give other time to join the queue
        System.out.println("Queued: " + lock.getQueueLength());
        lock.unlock();                                 // the last unlock() releases the lock
        other.join();
        System.out.println("isLocked = " + lock.isLocked());
    }
}
holdCount = 2
After one unlock(): holdCount = 1, isLocked = true
other: isHeldByCurrentThread = false
other: unlock() -> IllegalMonitorStateException
Queued: 1
other acquired the lock
isLocked = false

After the first unlock() the lock is still taken — the count is 1. That's the source of a common bug: a method acquires the lock twice (directly and through a method it calls) but releases it once, and other threads wait for no visible reason.

ReentrantLock method What it returns What it's for
getHoldCount() How many times the current thread has acquired the lock (0 if it doesn't own it) Checks in tests and assert
isHeldByCurrentThread() true if the current thread holds the lock assert lock.isHeldByCurrentThread() in methods that must be called under the lock
isLocked() Whether any thread holds the lock Monitoring, not synchronization
getQueueLength(), hasQueuedThreads() An estimate of the number of waiting threads / whether there are any Monitoring: the value may change right after the call
isFair() Whether the lock was created as fair Diagnostics

The Javadoc explicitly describes isLocked() and getQueueLength() as methods for monitoring system state. Don't build "if the lock is free, take it" logic on them: another thread can grab the lock between the check and the acquisition. That's what tryLock() is for.

tryLock(): Acquiring Without Waiting or With a Timeout

tryLock() tries to acquire the lock and immediately returns true or false without waiting. tryLock(time, unit) waits no longer than the given time. Both let a thread give up on a lock instead of getting stuck forever — and that's how you protect against deadlock when a thread needs two locks at once.

A synchronized monitor can't do this: a thread either gets it or waits indefinitely. The classic case is a transfer between two accounts running in opposite directions in two threads. A fixed lock order and nested tryLock with a timeout are covered in How to Avoid a Deadlock; here is a complete program with back-off and retries:

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TransferWithTryLock {
    static class Account {
        final Lock lock = new ReentrantLock();
        int balance;

        Account(int balance) {
            this.balance = balance;
        }
    }

    static final AtomicInteger retries = new AtomicInteger();

    static boolean transfer(Account from, Account to, int amount) throws InterruptedException {
        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
        while (System.nanoTime() < deadline) {
            if (from.lock.tryLock(10, TimeUnit.MILLISECONDS)) {   // holding nothing yet - OK to wait
                try {
                    if (to.lock.tryLock()) {                       // already holding the first - don't wait
                        try {
                            from.balance -= amount;
                            to.balance += amount;
                            return true;
                        } finally {
                            to.lock.unlock();
                        }
                    }
                } finally {
                    from.lock.unlock();                            // back off: release the first lock
                }
            }
            retries.incrementAndGet();
            Thread.sleep(ThreadLocalRandom.current().nextInt(1, 3)); // random pause against livelock
        }
        return false;                                              // didn't make it within a second
    }

    static void transferMany(Account from, Account to) {
        try {
            for (int i = 0; i < 1000; i++) {
                if (!transfer(from, to, 1)) {
                    System.out.println("Transfer not completed within 1 s");
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> transferMany(a, b), "a->b");
        Thread t2 = new Thread(() -> transferMany(b, a), "b->a");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("a = " + a.balance + ", b = " + b.balance
                + ", total = " + (a.balance + b.balance));
        System.out.println("Retries: " + retries.get());
    }
}
a = 1000, b = 1000, total = 2000
Retries: 23

The first line is the same on every run: a thousand transfers one way and a thousand the other, no money lost, no hang. The retry count changes from run to run and can be zero if the threads never collided. With nested synchronized (from) { synchronized (to) { … } } the same code would deadlock sooner or later.

Look at how differently the two locks are acquired. The thread waits for the first one with a timeout: while it holds nothing, waiting gets in nobody's way. The second one it takes without waiting: it already holds from, and waiting at that moment means meeting the "hold and wait" condition that every deadlock starts with. If it fails, release everything and try again. The random pause keeps the two threads from backing off and retrying in lockstep — otherwise you trade a deadlock for a livelock (see Deadlock, livelock and starvation).

tryLock() has uses that have nothing to do with deadlock, too: skip optional work if someone is already doing it (a background cache refresh, flushing statistics), or answer a client with "busy" instead of holding the request.

lockInterruptibly(): A Wait You Can Interrupt

A thread waiting in lock() can't be interrupted: interrupt() only sets the flag, and the thread keeps waiting for the lock. A thread in lockInterruptibly() reacts to an interrupt right away: it stops waiting and throws InterruptedException. That's why lockInterruptibly() is used wherever waiting must be cancellable — on pool shutdown, task cancellation or application exit.

import java.util.concurrent.locks.ReentrantLock;

public class InterruptibleExample {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread plain = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("plain: acquired the lock, interrupted flag = "
                        + Thread.currentThread().isInterrupted());
            } finally {
                lock.unlock();
            }
        }, "plain");
        Thread interruptible = new Thread(() -> {
            try {
                lock.lockInterruptibly();
                try {
                    System.out.println("interruptible: acquired the lock");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                System.out.println("interruptible: wait interrupted");
            }
        }, "interruptible");

        lock.lock();
        try {
            plain.start();
            interruptible.start();
            Thread.sleep(200);
            System.out.println("plain: " + plain.getState() + ", interruptible: " + interruptible.getState());

            plain.interrupt();
            interruptible.interrupt();
            interruptible.join();
            Thread.sleep(200);
            System.out.println("plain after interrupt(): " + plain.getState());
        } finally {
            lock.unlock();
        }
        plain.join();
    }
}
plain: WAITING, interruptible: WAITING
interruptible: wait interrupted
plain after interrupt(): WAITING
plain: acquired the lock, interrupted flag = true

Both threads wait in WAITING, but they react to interrupt() differently. interruptible leaves the wait with an exception and never gets the lock. plain keeps waiting and gets the lock only after unlock() in main — with the interrupted flag set: lock() remembers the interrupt and restores the flag after acquiring, so the code that follows can check it.

synchronized has no equivalent: a BLOCKED thread ignores interrupt() entirely. That's why a deadlock on monitors can't be broken without restarting the JVM, while a deadlock on locks acquired through lockInterruptibly() or tryLock(time, unit) can.

Fair Locks: new ReentrantLock(true)

A fair lock — new ReentrantLock(true) — hands a released lock to the thread that has been waiting longest, in queue order (FIFO). By default ReentrantLock is unfair: a thread that has just arrived can grab the lock ahead of the waiting ones. Fairness protects against starvation but noticeably lowers throughput.

Why is the unfair lock faster? When the lock is released, a waiting thread has to be woken up, and that takes time. In that gap an unfair lock gives itself to whoever is already running on a CPU and asking for it right now (barging) — no extra context switch. A fair lock sends that thread to the back of the queue. The ReentrantLock Javadoc warns that programs using fair locks under contention may be slower, "often much slower".

What does this program print? main holds the lock, a second thread joins the queue, then main releases the lock and immediately asks for it again.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class FairnessExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("unfair, lock():   " + race(false, false));
        System.out.println("fair, lock():     " + race(true, false));
        System.out.println("fair, tryLock():  " + race(true, true));
    }

    static List<String> race(boolean fair, boolean viaTryLock) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock(fair);
        List<String> order = new ArrayList<>();           // modified only under lock
        lock.lock();
        Thread waiter = new Thread(() -> {
            lock.lock();
            try {
                order.add("waiter");
            } finally {
                lock.unlock();
            }
        });
        waiter.start();
        Thread.sleep(100);                                // waiter is now queued
        lock.unlock();                                    // release…
        boolean acquired = viaTryLock && lock.tryLock();  // …and want it back right away
        if (!acquired) {
            lock.lock();
        }
        try {
            order.add("main");
        } finally {
            lock.unlock();
        }
        waiter.join();
        return order;
    }
}
unfair, lock():   [main, waiter]
fair, lock():     [waiter, main]
fair, tryLock():  [main, waiter]

The second line is guaranteed: a fair lock() sees that waiter is already queued and puts main behind it. The first and third lines are the result of a race with the waking thread. The first one almost always looks like this in practice: main grabs the lock before waiter wakes up. The third one is less stable: in our runs on JDK 22, main won the lock in roughly 6 runs out of 10, and in the rest waiter got it first — tryLock() barges ahead of the queue only if the lock is still free at the moment of the call. The third line demonstrates a rule from the Javadoc: the no-argument tryLock() breaks fairness and takes a free lock even when other threads are queued. If you need fairness for a no-wait attempt too, call tryLock(0, TimeUnit.SECONDS) — it respects the queue.

One more caveat from the docs: a fair lock doesn't make the thread scheduler fair. It only orders the queue of threads waiting for this lock. Reach for it when starvation of a particular thread is actually observed (more on starvation in thread priorities and starvation), not "just in case".

Lock vs synchronized: Which One to Use

Use synchronized by default: you can't forget to release it, the code is shorter, and since Java 6 its performance is comparable to ReentrantLock. Pick Lock when you need one of its features: tryLock with a timeout, an interruptible wait, a fair queue, several conditions on one lock, or separate read and write locks.

Feature synchronized ReentrantLock
Syntax Method modifier or a synchronized (obj) { … } block Explicit lock() and unlock() calls
Release Automatic on any exit from the block, including an exception Manual, unlock() in finally
Acquire without waiting No tryLock()
Timeout No tryLock(time, unit)
Interruptible wait No: a BLOCKED thread ignores interrupt() lockInterruptibly()
Fairness No guarantees new ReentrantLock(true)
Wait conditions One wait set per object: wait()/notify() Any number of Conditions on one lock
Reentrancy Yes Yes, the count is available via getHoldCount()
Separate read and write No ReentrantReadWriteLock
State of a waiting thread BLOCKED WAITING or TIMED_WAITING
Visibility (happens-before) A monitor exit happens-before the next entry Same guarantees: unlock() happens-before the next lock()
Performance Comparable since Java 6; in Java 5 ReentrantLock was noticeably faster under contention
Virtual threads Java 21–23: blocking inside synchronized pins the virtual thread to its carrier; since Java 24 (JEP 491) it doesn't No pinning in any version

The last row is the only reason teams on Java 21–23 rewrote synchronized into ReentrantLock without any new logic requirements: long operations under a monitor tied up the carrier threads of virtual threads. Since Java 24 that argument is gone (details in synchronized and virtual threads). Visibility works the same way in both cases, see synchronized and happens-before.

Often the right answer is neither. A counter is an AtomicInteger (atomic classes), a shared map is a ConcurrentHashMap, a queue between threads is a BlockingQueue (concurrent collections), and a set of background tasks is an ExecutorService. They already contain the locks they need, so there's no lock/unlock pattern to get wrong.

Condition: await() and signal() Instead of wait() and notify()

A Condition is a wait condition bound to a Lock; you create it with lock.newCondition(). Its await(), signal() and signalAll() methods work like wait(), notify() and notifyAll() on a monitor, but one lock can have several conditions. Threads waiting for different things then sit in different queues, and signal() wakes only a thread that is waiting for the right event.

The mechanics match wait(): you may call await() only while holding the lock, the lock is released for the duration of the wait and reacquired before the call returns. The wait is always wrapped in a while loop that checks the condition — for the same reasons as with wait() (explained in Why wait() Is Called in a while Loop).

Condition method Monitor counterpart What it returns and when it ends
await() wait() After signal()/signalAll(), an interrupt (InterruptedException) or a spurious wakeup
await(long time, TimeUnit unit) wait(ms) false if the time ran out; with wait(ms) you can't tell
awaitNanos(long nanos) — Remaining time in nanoseconds (0 or less means timeout), handy in a while loop
awaitUninterruptibly() — Ignores interrupts, the flag is preserved
awaitUntil(Date deadline) — false if the deadline has passed
signal() notify() Wakes one thread waiting on this condition
signalAll() notifyAll() Wakes all threads waiting on this condition

Calling any of them without holding a ReentrantLock ends in IllegalMonitorStateException — just like wait() outside synchronized.

The example is a bounded buffer for two items with two conditions: the producer waits on notFull, the consumer on notEmpty. The consumer takes an item every 100 ms, so the producer keeps running into a full buffer.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBufferExample {
    static class BoundedBuffer<T> {
        private final Deque<T> items = new ArrayDeque<>();
        private final int capacity;
        private final ReentrantLock lock = new ReentrantLock();
        private final Condition notFull = lock.newCondition();   // producers wait here
        private final Condition notEmpty = lock.newCondition();  // consumers wait here

        BoundedBuffer(int capacity) {
            this.capacity = capacity;
        }

        void put(T item) throws InterruptedException {
            lock.lock();
            try {
                while (items.size() == capacity) {
                    notFull.await();             // releases lock and waits for space
                }
                items.addLast(item);
                System.out.println("put " + item);
                notEmpty.signal();               // wake a consumer, not another producer
            } finally {
                lock.unlock();
            }
        }

        T take() throws InterruptedException {
            lock.lock();
            try {
                while (items.isEmpty()) {
                    notEmpty.await();
                }
                T item = items.removeFirst();
                System.out.println("took " + item);
                notFull.signal();
                return item;
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BoundedBuffer<Integer> buffer = new BoundedBuffer<>(2);
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    buffer.put(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    Thread.sleep(100);           // slow consumer
                    buffer.take();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
    }
}
put 1
put 2
took 1
put 3
took 2
put 4
took 3
put 5
took 4
took 5

The consumer's pauses fix the order of the lines, so the output is the same on every run. The producer fills both slots right away and goes to sleep on notFull. Each "took" frees a slot and wakes it, and "put" is printed after "took" because the producer waits until the consumer releases the lock.

The key point here is signal() instead of signalAll(). On a single monitor, producers and consumers would wait in one shared wait set, and notify() could wake the wrong thread — the wait()/notify() lesson walks through such a hang step by step (notify() vs notifyAll()). With two conditions, only producers wait on notFull and only consumers on notEmpty, so a single signal() always reaches the right group and there are no wasted wakeups. Add as many producers and consumers as you like — the code stays correct.

You don't need to write such a buffer in production code: ArrayBlockingQueue is built exactly this way internally — one ReentrantLock and two conditions, notEmpty and notFull (see BlockingQueue in Java). Condition is for cases where the wait condition is your own and doesn't fit the ready-made classes.

await(), not wait()

Condition is an ordinary object, so it also has the wait() and notify() methods inherited from Object. The line notFull.wait() compiles without a warning, but it uses the monitor of the condition object, not the ReentrantLock, and immediately fails with IllegalMonitorStateException: the thread doesn't own that object's monitor. IDE autocompletion offers both — the one you want is await().

ReadWriteLock and ReentrantReadWriteLock

ReadWriteLock is a pair of linked locks: any number of threads can hold readLock() at the same time as long as nobody is writing, while writeLock() is held by a single thread with no readers and no other writers. The main implementation is ReentrantReadWriteLock. It pays off when data is read often and for a long time but changed rarely: a cache, configuration, a reference table.

The configuration example shows three things: readers don't block each other, a read lock can't be upgraded to a write lock, and a write lock can be downgraded to a read lock.

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {
    private static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private static final Map<String, String> config = new HashMap<>();

    static String get(String key) {
        rwLock.readLock().lock();
        try {
            return config.get(key);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    static void put(String key, String value) {
        rwLock.writeLock().lock();
        try {
            config.put(key, value);
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        put("timeout", "30");

        // 1. Two readers at once, the writer has to wait
        Runnable longRead = () -> {
            rwLock.readLock().lock();
            try {
                pause(300);
            } finally {
                rwLock.readLock().unlock();
            }
        };
        Thread r1 = new Thread(longRead);
        Thread r2 = new Thread(longRead);
        r1.start();
        r2.start();
        pause(100);
        System.out.println("Readers now: " + rwLock.getReadLockCount());
        System.out.println("Writer while readers hold it, tryLock(): " + rwLock.writeLock().tryLock());
        r1.join();
        r2.join();
        System.out.println("timeout = " + get("timeout"));

        // 2. Upgrading read -> write is impossible
        rwLock.readLock().lock();
        try {
            boolean upgraded = rwLock.writeLock().tryLock(1, TimeUnit.SECONDS); // lock() would wait forever
            System.out.println("Upgrade read -> write: " + upgraded);
        } finally {
            rwLock.readLock().unlock();
        }

        // 3. Downgrading write -> read works
        rwLock.writeLock().lock();
        try {
            config.put("timeout", "60");
            rwLock.readLock().lock();          // take read while still holding write
        } finally {
            rwLock.writeLock().unlock();       // now holding only read
        }
        try {
            System.out.println("After downgrade: timeout = " + config.get("timeout")
                    + ", isWriteLocked = " + rwLock.isWriteLocked()
                    + ", readers = " + rwLock.getReadLockCount());
        } finally {
            rwLock.readLock().unlock();
        }
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
Readers now: 2
Writer while readers hold it, tryLock(): false
timeout = 30
Upgrade read -> write: false
After downgrade: timeout = 60, isWriteLocked = false, readers = 1

The line "Upgrade read -> write: false" appears after one second. The ban on upgrading is spelled out in the ReentrantReadWriteLock Javadoc: the write lock is granted only when no thread holds a read lock, including the requesting thread itself. With writeLock().lock() instead of tryLock, the thread would wait for itself to release the read lock — forever, with no second party involved and no deadlock reported in a thread dump. If two readers need an upgrade at the same time, they block each other. The correct way: release read, acquire write and check the data again — another writer may have changed it while you held no lock.

Downgrading, on the other hand, is allowed and useful: a thread has updated the data and wants to keep reading it without letting other writers in, while no longer blocking readers.

A few more details about ReentrantReadWriteLock. The constructor takes a fairness flag, just like ReentrantLock. Only the write lock supports Condition; readLock().newCondition() throws UnsupportedOperationException. And for short operations a read-write lock can be slower than a plain one: tracking readers costs more than a single ReentrantLock. If you're protecting a map, a ConcurrentHashMap is usually simpler than a HashMap behind a ReadWriteLock — its reads take no lock at all (see ConcurrentHashMap).

StampedLock: Optimistic Reads

StampedLock (Java 8) is a lock with three modes: writing, reading and optimistic reading. In optimistic mode a thread blocks nothing at all: it gets a "stamp" from tryOptimisticRead(), reads the fields, and then calls validate(stamp) to check whether a write happened in the meantime. If one did, it rereads under a regular read lock.

private final StampedLock sl = new StampedLock();
private double x, y;

double distanceFromOrigin() {
    long stamp = sl.tryOptimisticRead();    // no locking
    double curX = x, curY = y;              // read into local variables
    if (!sl.validate(stamp)) {              // a write happened - retry under a read lock
        stamp = sl.readLock();
        try {
            curX = x;
            curY = y;
        } finally {
            sl.unlockRead(stamp);
        }
    }
    return Math.hypot(curX, curY);
}

When writes are rare, readers almost never take the lock and don't get in the writer's way. The price is a set of restrictions that trip people up when they switch from ReentrantReadWriteLock. StampedLock is not reentrant: a second writeLock() in the same thread waits for itself forever. It doesn't implement the Lock interface (there are asReadLock() and asWriteLock() views), doesn't support Condition, and must be released with the stamp you got when acquiring it. It's used in small classes with short read sections; everywhere else ReentrantReadWriteLock is simpler.

Where Developers Go Wrong with Lock

Nearly every mistake with Lock comes from manual release: the compiler doesn't check that every lock() has a matching unlock(), and the program usually doesn't crash — it silently stops. The typical slips and their symptoms:

Mistake What happens How to fix it
unlock() not in finally An exception or early return leaves the lock taken; other threads wait forever lock(); try { … } finally { unlock(); }
lock() or lockInterruptibly() inside try If acquisition fails, finally throws IllegalMonitorStateException and hides the original exception Acquire on the line before try
unlock() after tryLock() returned false IllegalMonitorStateException try/finally only inside the if (lock.tryLock()) branch
unlock() called fewer times than lock() Reentry left getHoldCount() above zero — the lock isn't released One try/finally per acquisition; in tests — assert !lock.isHeldByCurrentThread() after the operation
new ReentrantLock() inside a method Every call creates its own lock — threads don't exclude each other, the race remains A private final field shared by all threads
synchronized (lock), lock.wait(), condition.notify() The object's monitor is used instead of the lock itself; wait()/notify() without the monitor — IllegalMonitorStateException Only Lock and Condition methods: lock(), await(), signal()
if instead of while around await() After a spurious wakeup or a "stolen" condition the thread works with wrong data while (!condition) cond.await();
writeLock().lock() while holding readLock() The thread waits for itself forever Release read, acquire write, recheck the data

A hang caused by a forgotten unlock() shows up in a thread dump. jstack -l <pid> prints a "Locked ownable synchronizers" section for each thread, which tells you which thread holds a ReentrantLock. And if threads wait for each other's locks in a cycle, ThreadMXBean.findDeadlockedThreads() finds cycles on ReentrantLock too, not just on monitors (see How to detect a deadlock). A lock left behind by a dead thread, as in the ForgottenUnlock example, is invisible to the deadlock detector: there's no cycle, just an owner that no longer exists.

Frequently Asked Questions

Can I use ReentrantLock with try-with-resources?

Not directly: Lock doesn't implement AutoCloseable. You can write a small wrapper whose static method calls lock() and returns an object whose close() calls unlock(): try (var ignored = Locked.acquire(lock)) { … }. It guarantees the release, but it allocates an object per acquisition and doesn't fit tryLock(), where you don't always need to release. That's why the JDK and most projects stick with plain try/finally — see The lock() / try / finally Pattern.

How do I find out which thread holds a ReentrantLock?

The quickest way is toString(): it returns something like java.util.concurrent.locks.ReentrantLock@1b6d3586[Locked by thread worker] or [Unlocked]. The getOwner() method is protected and available only in a subclass. In a running application jstack -l <pid> shows the owner: in the "Locked ownable synchronizers" section of the owning thread you'll see a ReentrantLock$NonfairSync (or FairSync) object.

Can a ReentrantLock be released from another thread?

No. A ReentrantLock has an owner, and unlock() from any other thread throws IllegalMonitorStateException. If your scenario needs one thread to acquire and another to release, you need a Semaphore with one permit rather than a lock: it has no owner, and any thread can call release().

Should a Lock field be declared volatile?

No, private final is enough. final guarantees that all threads see the same lock object once the owning object is constructed, and visibility of the protected data comes from the lock itself: unlock() happens-before the next lock(). Without final the field can be reassigned by accident, and threads end up on different locks — the same mistake as synchronizing on a mutable field with synchronized.

Comments

Please log in or register to have a possibility to add comment.