Condition objects: waiting with a Lock
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)wait() and notify() work only with synchronized. When you protect data with a ReentrantLock, threads wait and wake up through Condition objects instead, and one lock can have several of them, one for each thing a thread may be waiting for.
newCondition(), await() and signal()
A Condition is a waiting room that belongs to one lock. A thread calls await() to release the lock and sleep until another thread calls signal() on the same condition.
A Condition is a waiting room that belongs to one lock. You create it with lock.newCondition(). await() releases the lock and puts the thread to sleep until another thread calls signal() (wake one waiter) or signalAll() (wake all waiters) on the same condition.
lock.lock();try { while (parcel == null) { // check again after every wake-up ready.await(); // releases the lock while waiting } // the parcel is here, and we hold the lock again} finally { lock.unlock();}The rules are the same as for wait(). You must hold the lock when you call await() or signal(). A woken thread takes the lock back before await() returns. And you always wait inside a while loop that re-checks the condition, because a thread can wake up when the condition is still false (a spurious wakeup, or another thread got there first).
Example 1 · Waiting for a packed order with await() and signal()
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
class ParcelCounter { private final ReentrantLock lock = new ReentrantLock(); private final Condition ready = lock.newCondition(); private String parcel = null;
void serve(String item) { lock.lock(); try { parcel = item; ready.signal(); // wake the waiting customer } finally { lock.unlock(); } }
String collect() throws InterruptedException { lock.lock(); try { while (parcel == null) { ready.await(); // releases the lock while waiting } String item = parcel; parcel = null; return item; } finally { lock.unlock(); } }}
public class ConditionBasicsDemo { public static void main(String[] args) throws InterruptedException { ParcelCounter counter = new ParcelCounter();
Thread customer = new Thread(() -> { try { System.out.println("customer: waiting for order 42"); String item = counter.collect(); System.out.println("customer: got " + item); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "customer"); customer.start();
while (customer.getState() != Thread.State.WAITING) { Thread.sleep(1); // wait until the customer is waiting at the counter } System.out.println("packer: laptop is packed"); counter.serve("laptop"); customer.join(); }}customer: waiting for order 42 packer: laptop is packed customer: got laptop
What this code does
- The customer finds
parcel == nulland callsawait(). That releases the lock, so the packer can enterserve()while the customer sleeps. serve()sets the parcel and callssignal(). The customer wakes, takes the lock back, checks thewhilecondition again and leaves with the laptop.- Both
await()andsignal()are called while holding the lock, exactly likewait()andnotify()insidesynchronized.
Separate notFull and notEmpty conditions
Separate conditions mean one Condition per reason for waiting. A bounded buffer has two reasons: producers wait while it is full, consumers wait while it is empty. So it gets two conditions on the same lock: notFull and notEmpty.
Example 2 · A dispatch queue with notFull and notEmpty
import java.util.ArrayDeque;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
class DispatchQueue { private final ReentrantLock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); private final ArrayDeque<String> orders = new ArrayDeque<>(); private final int capacity;
DispatchQueue(int capacity) { this.capacity = capacity; }
void put(String order) throws InterruptedException { lock.lock(); try { while (orders.size() == capacity) { notFull.await(); // producers wait here } orders.addLast(order); notEmpty.signal(); // wake a consumer, never a producer } finally { lock.unlock(); } }
String take() throws InterruptedException { lock.lock(); try { while (orders.isEmpty()) { notEmpty.await(); } String order = orders.removeFirst(); notFull.signal(); // wake a producer, never a consumer return order; } finally { lock.unlock(); } }}
public class TwoConditionsDemo { public static void main(String[] args) throws InterruptedException { DispatchQueue queue = new DispatchQueue(2);
Thread warehouse = new Thread(() -> { try { for (int i = 1; i <= 6; i++) { queue.put("order-" + i); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "warehouse");
Thread courier = new Thread(() -> { try { for (int i = 1; i <= 6; i++) { System.out.println("courier picked up " + queue.take()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "courier");
warehouse.start(); courier.start(); warehouse.join(); courier.join(); System.out.println("All orders dispatched"); }}courier picked up order-1 courier picked up order-2 courier picked up order-3 courier picked up order-4 courier picked up order-5 courier picked up order-6 All orders dispatched
What this code does
- The queue holds at most 2 orders. When it is full, the warehouse waits on
notFull; when it is empty, the courier waits onnotEmpty. putsignals onlynotEmptyandtakesignals onlynotFull, so a signal always reaches a thread that can use it.- Only the courier prints, and the queue is first-in first-out, so the orders come out as 1 to 6 on every run.
With synchronized, all waiters share one waiting room. A producer that calls notify() might wake another producer, which finds the buffer still full and goes back to sleep. That is why the wait/notify version needs notifyAll(), which wakes everybody. With two conditions, put signals notEmpty and wakes only a consumer; take signals notFull and wakes only a producer. Every waiter in a room wants the same thing, so signal() is enough and nobody is woken for nothing.
Bounded buffer rewritten with a Lock
A bounded buffer is a queue with a fixed capacity, shared by producer and consumer threads. With a ReentrantLock it has the same shape as the wait/notify version: lock, while the condition is false await(), change the queue, signal the other side, unlock in finally.
Example 3 · Bounded buffer: two packers and two couriers
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.TreeSet;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
class BoundedBuffer { private final ReentrantLock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); private final ArrayDeque<Integer> items = new ArrayDeque<>(); private final int capacity;
BoundedBuffer(int capacity) { this.capacity = capacity; }
void put(int item) throws InterruptedException { lock.lock(); try { while (items.size() == capacity) { notFull.await(); } items.addLast(item); notEmpty.signal(); } finally { lock.unlock(); } }
int take() throws InterruptedException { lock.lock(); try { while (items.isEmpty()) { notEmpty.await(); } int item = items.removeFirst(); notFull.signal(); return item; } finally { lock.unlock(); } }}
public class BoundedBufferLockDemo { public static void main(String[] args) throws InterruptedException { BoundedBuffer buffer = new BoundedBuffer(5); List<List<Integer>> received = List.of(new ArrayList<>(), new ArrayList<>()); List<Thread> threads = new ArrayList<>();
for (int k = 0; k < 2; k++) { int start = k * 1000; // packer-1: 1..500, packer-2: 1001..1500 threads.add(new Thread(() -> { try { for (int i = 1; i <= 500; i++) { buffer.put(start + i); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "packer-" + (k + 1))); } for (int r = 0; r < 2; r++) { List<Integer> mine = received.get(r); threads.add(new Thread(() -> { try { for (int i = 0; i < 500; i++) { mine.add(buffer.take()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "courier-" + (r + 1))); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); }
TreeSet<Integer> all = new TreeSet<>(received.get(0)); all.addAll(received.get(1)); System.out.println("Orders taken by couriers: " + (received.get(0).size() + received.get(1).size())); System.out.println("Different orders: " + all.size()); System.out.println("First and last: " + all.first() + " and " + all.last()); }}Orders taken by couriers: 1000 Different orders: 1000 First and last: 1 and 1500
What this code does
- Two producers put 500 orders each into a buffer of size 5, and two consumers take 500 each. Every thread waits on the right condition when it cannot go on.
- How the 1000 orders are split between the couriers changes from run to run, so each courier keeps its own list and
mainchecks the totals afterjoin(). - 1000 orders taken and 1000 different numbers means nothing was lost or delivered twice.
This is close to how ArrayBlockingQueue is built inside the JDK: one ReentrantLock and two conditions named notEmpty and notFull. In real code you would use ArrayBlockingQueue; writing it once yourself shows what put() and take() do for you.
Comparison with wait and notify
Condition versus wait/notify is a choice that follows the lock you use: synchronized goes with wait/notify/notifyAll, a Lock goes with await/signal/signalAll. Mixing them up throws IllegalMonitorStateException.
Example 4 · Mistakes: await without the lock, and wait() on a Condition
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
public class ConditionMistakesDemo { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Condition seatFree = lock.newCondition();
try { seatFree.await(); // lock not held } catch (IllegalMonitorStateException e) { System.out.println("await() without the lock: IllegalMonitorStateException"); }
try { seatFree.signal(); // lock not held } catch (IllegalMonitorStateException e) { System.out.println("signal() without the lock: IllegalMonitorStateException"); }
lock.lock(); try { seatFree.wait(); // wrong method: Object.wait() } catch (IllegalMonitorStateException e) { System.out.println("wait() instead of await(): IllegalMonitorStateException"); } finally { lock.unlock(); } }}await() without the lock: IllegalMonitorStateException signal() without the lock: IllegalMonitorStateException wait() instead of await(): IllegalMonitorStateException
What this code does
await()andsignal()need the condition's lock. Without it, they throw at once instead of silently doing nothing.seatFree.wait()compiles because every object haswait(). It needs the monitor of theConditionobject itself, whichlock.lock()does not give, so it throws too.- With a
Lock, the words areawait,signalandsignalAll;waitandnotifybelong tosynchronized.
Example 5 · await with a timeout: know whether you were signalled
import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
class OtpBox { private final ReentrantLock lock = new ReentrantLock(); private final Condition arrived = lock.newCondition(); private String otp = null;
void deliver(String code) { lock.lock(); try { otp = code; arrived.signalAll(); } finally { lock.unlock(); } }
String waitForOtp(long ms) throws InterruptedException { lock.lock(); try { long nanosLeft = TimeUnit.MILLISECONDS.toNanos(ms); while (otp == null) { if (nanosLeft <= 0) { return "no OTP within " + ms + " ms"; } nanosLeft = arrived.awaitNanos(nanosLeft); // returns the time still left } return "OTP " + otp; } finally { lock.unlock(); } }}
public class AwaitTimeoutDemo { public static void main(String[] args) throws InterruptedException { OtpBox box = new OtpBox(); System.out.println("First try: " + box.waitForOtp(100));
Thread sms = new Thread(() -> box.deliver("4821"), "sms-gateway"); sms.start(); System.out.println("Second try: " + box.waitForOtp(2000)); sms.join(); }}First try: no OTP within 100 ms Second try: OTP 4821
What this code does
- Nobody delivers an OTP during the first 100 ms, so the wait ends by itself and the method reports it.
awaitNanosreturns how much time is left. Using it in thewhileloop keeps the total wait at 100 ms even after a spurious wakeup.- In the second try the
sms-gatewaythread delivers the code,signalAll()wakesmain, and the loop ends long before 2 seconds.
Conditions add a few features on top of wait and notify:
- Many conditions per lock, so each kind of waiter has its own room and
signal()wakes the right kind. await(time, unit)returnsfalseif the time ran out, so you know whether you were signalled.awaitUninterruptibly()for the rare wait that must not be cancelled.- A fair lock also makes woken threads take the lock back in a fair order.
Condition is also a normal object, so cond.wait() compiles. It uses the object's own monitor, not your lock, and throws IllegalMonitorStateException. Always call await().Next step
Check your understanding
12 quick questions