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 synchronizedjava.util.concurrent.locks
ReentrantLockAbstractQueuedSynchronizerintlock()LockSupport.parkunlock()
A Conditionwaitnotifyawait()signal()
| Capability | synchronized | ReentrantLock | ReentrantReadWriteLock |
|---|---|---|---|
| Since | Java 1.0 | Java 5 | Java 5 |
| Released automatically | Yes, at the end of the block | No: unlock()finally | No: unlock()finally |
| Try, or give up after a timeout | No | tryLock()tryLock(time, unit) | Yes, on each lock |
| Stop waiting when interrupted | No | lockInterruptibly() | Yes |
| Wait queues per lock | One (waitnotify | Any number of Condition | Conditions on the write lock |
| Fair ordering option | No | Yes | Yes |
| Concurrent readers | No | No | Yes |
| Best for | Most code | Timeouts, interruptible waits, several conditions | Read-mostly data with long reads |
The memory effects are the same as for synchronizedunlock()lock()StampedLock
ReentrantLock basics
An account guarded by a ReentrantLock
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:
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
, thenlock() , thentry inunlock() . Withfinally outside thelock() , a failure to lock never reachestry , and an exception inside the guarded code can never leave the lock held forever.unlock - Inside
, the same thread locked twice and the hold count was 2. A non-reentrant lock would have deadlocked on itself there.deposit returned false while the holder thread kept the lock, so the caller can report "busy" instead of blocking. After the holder finished, the untimedtryLock(100, MILLISECONDS) succeeded at once.tryLock()- The waiter in
was in statelockInterruptibly() , notWAITING as withBLOCKED , and it gave up when interrupted. A thread waiting to enter asynchronized block cannot be interrupted.synchronized - Calling
from a thread that does not hold the lock throwsunlock() . Unlike a semaphore, a lock has an owner.IllegalMonitorStateException
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 synchronizedtryLock
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:
synchronized: both finished? false, deadlocked threads found by ThreadMXBean: 2
tryLock: both finished, C=1100 D=900, total still 2000, needed retries: true
- With
, neither transfer finished, andsynchronized 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 (ThreadMXBean.findDeadlockedThreads() , orjstack ) reports the same deadlock.jcmd PID Thread.print - With
, 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.tryLock - 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.
is the tool when no such order exists.tryLock
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 waitnotifyAll
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:
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.
sits in aawait() loop, not anwhile . A woken thread must check the condition again, because another thread may have taken the slot first, and becauseif may return spuriously, which theawait Javadoc explicitly allows.Condition signalsput andnotEmpty signalstake , so a producer only ever wakes a consumer and vice versa. With a single wait queue,notFull could wake another producer that finds the buffer still full; that is why code withnotify usually needswait , which wakes everyone.notifyAll- This is essentially how
is implemented. In application code, use theArrayBlockingQueueBlockingQueue classes rather than writing your own.
Fair locks and what fairness costs
new ReentrantLock(true)
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):
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
barges even on a fair lock;tryLock() respects fairness.tryLock(0, unit)
ReadWriteLock: many readers, one writer
A ReentrantReadWriteLock
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:
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
they would have taken 200 ms, one after another.ReentrantLock - Upgrading does not work: a thread holding the read lock could not get the write lock, and
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.writeLock().lock() - 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
or an immutable map swapped through aConcurrentHashMap field is often simpler; for optimistic reads that take no lock at all, seevolatileStampedLock .
Choosing a lock
| Situation | Use |
|---|---|
| Ordinary mutual exclusion | synchronized |
| Give up after a timeout, or avoid deadlock without a lock order | ReentrantLock.tryLock(time, unit) |
| A waiting thread must be cancellable | lockInterruptibly() |
| Several wait conditions on the same state | One ReentrantLockCondition |
| Threads must not starve | new ReentrantLock(true) |
| Long reads, rare writes | ReentrantReadWriteLock |
| Very frequent short reads | |
| A single counter or reference |
Before Java 24, a virtual thread that blocked inside synchronizedReentrantLock