Skip to lesson

Producer-consumer with wait and notify

In a producer-consumer design, some threads make items (producers) and other threads use them (consumers), with a shared store in between. An online store's warehouse packs orders, riders carry them, and the pickup shelf in between can hold only a few bags.

The bounded buffer problem

Producer-consumer is a pattern where some threads put work items into a shared queue and other threads take them out and process them.

A bounded buffer is a shared store with a fixed capacity between producers and consumers. A producer is a thread that adds items; a consumer is a thread that removes and uses them.

Producer-consumer. Two producer threads put orders into a BlockingQueue with capacity 3, which holds order 1 and order 2 and one free place. Two consumer threads take orders from the queue. put() waits when the queue is full and take() waits when it is empty.

Example 1 · A shelf without waiting just fails

ShelfNoWaitDemo.javaJava
import java.util.ArrayDeque;import java.util.Queue;
class ShelfNoWait {    private final Queue<String> bags = new ArrayDeque<>();    private final int capacity;
    ShelfNoWait(int capacity) {        this.capacity = capacity;    }
    boolean put(String bag) {        if (bags.size() == capacity) {            return false;                 // full: what should the warehouse do now?        }        bags.add(bag);        return true;    }
    String take() {        return bags.poll();               // empty: returns null    }}
public class ShelfNoWaitDemo {    public static void main(String[] args) {        ShelfNoWait shelf = new ShelfNoWait(3);        for (int i = 1; i <= 4; i++) {            System.out.println("put ORD-" + i + ": " + shelf.put("ORD-" + i));        }        for (int i = 1; i <= 4; i++) {            System.out.println("take: " + shelf.take());        }    }}
Output
put ORD-1: true
put ORD-2: true
put ORD-3: true
put ORD-4: false
take: ORD-1
take: ORD-2
take: ORD-3
take: null

What this code does

  • The pickup shelf holds 3 bags. The fourth put fails because the shelf is full, and the fourth take gets null because it is empty.
  • With threads, failing is the wrong answer. The warehouse should wait until a rider makes room, and a rider should wait until a bag arrives. That waiting is what the bounded buffer adds.
  • Full buffer: the producer must wait until a consumer makes room.
  • Empty buffer: the consumer must wait until a producer adds an item.
  • The fixed capacity also stops a fast producer from filling all memory.

The two sides run at different speeds, so two things must never happen: a producer adding to a full buffer, and a consumer taking from an empty one. A plain queue cannot handle this on its own.

Waiting while full and while empty

The buffer needs two guards: put waits while (size == capacity) and take waits while (isEmpty()). After changing the buffer, each side calls notifyAll() to wake threads waiting on the other side.

Java
synchronized void put(String item) throws InterruptedException {    while (items.size() == capacity) wait();    items.add(item);    notifyAll();}
synchronized String take() throws InterruptedException {    while (items.isEmpty()) wait();    String item = items.remove();    notifyAll();    return item;}

Both guards matter. Without the full check the buffer grows past its capacity; without the empty check a consumer removes from an empty queue and crashes.

Example 2 · A bounded buffer with wait and notifyAll

BoundedBufferDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
class BoundedBuffer {    private final Queue<String> items = new ArrayDeque<>();    private final int capacity;    private boolean everOverCapacity = false;
    BoundedBuffer(int capacity) {        this.capacity = capacity;    }
    synchronized void put(String item) throws InterruptedException {        while (items.size() == capacity) {            wait();        }        items.add(item);        if (items.size() > capacity) {            everOverCapacity = true;        }        notifyAll();                          // a consumer may be waiting for "not empty"    }
    synchronized String take() throws InterruptedException {        while (items.isEmpty()) {            wait();        }        String item = items.remove();        notifyAll();                          // a producer may be waiting for "not full"        return item;    }
    synchronized boolean everOverCapacity() {        return everOverCapacity;    }}
public class BoundedBufferDemo {    public static void main(String[] args) throws InterruptedException {        BoundedBuffer shelf = new BoundedBuffer(3);        List<String> delivered = new ArrayList<>();
        Thread warehouse = new Thread(() -> {            try {                for (int i = 1; i <= 8; i++) {                    shelf.put("ORD-" + i);               // waits when 3 bags are on the shelf                }            } catch (InterruptedException e) {                return;            }        }, "warehouse");
        Thread rider = new Thread(() -> {            try {                for (int i = 1; i <= 8; i++) {                    delivered.add(shelf.take());                    Thread.sleep(20);                }            } catch (InterruptedException e) {                return;            }        }, "rider");
        warehouse.start();        rider.start();        warehouse.join();        rider.join();
        System.out.println("Delivered: " + delivered);        System.out.println("Shelf ever over capacity: " + shelf.everOverCapacity());    }}
Output
Delivered: [ORD-1, ORD-2, ORD-3, ORD-4, ORD-5, ORD-6, ORD-7, ORD-8]
Shelf ever over capacity: false

What this code does

  • The warehouse is much faster than the rider, who needs 20 ms to ride to the customer after each bag, so it fills the shelf and then waits in put (guard: size == capacity). Each take makes room and calls notifyAll(), which wakes the warehouse.
  • The rider waits in take whenever the shelf is empty (guard: isEmpty()), and every put wakes it. The queue keeps the bags in order, so they are delivered ORD-1 to ORD-8.
  • delivered is used only by the rider and read by main after join(), so it needs no lock.

Example 3 · Bug: leave out a check and the buffer breaks

MissingCheckDemo.javaJava
import java.util.ArrayDeque;import java.util.Queue;
class LeakyBuffer {    private final Queue<String> items = new ArrayDeque<>();    private final int capacity;    private int mostAtOnce = 0;
    LeakyBuffer(int capacity) {        this.capacity = capacity;    }
    synchronized void putNoFullCheck(String item) {        items.add(item);                       // no "while full, wait"        mostAtOnce = Math.max(mostAtOnce, items.size());        notifyAll();    }
    synchronized String takeNoEmptyCheck() {        String item = items.remove();          // no "while empty, wait"        notifyAll();        return item;    }
    synchronized int mostAtOnce() {        return mostAtOnce;    }}
public class MissingCheckDemo {    public static void main(String[] args) throws InterruptedException {        LeakyBuffer shelf = new LeakyBuffer(3);        Thread warehouse = new Thread(() -> {            for (int i = 1; i <= 8; i++) {                shelf.putNoFullCheck("ORD-" + i);            }        }, "warehouse");        warehouse.start();        warehouse.join();        System.out.println("No full check:  most bags on the shelf at once = " + shelf.mostAtOnce() + " (capacity 3)");
        LeakyBuffer empty = new LeakyBuffer(3);        Thread rider = new Thread(() -> {            try {                empty.takeNoEmptyCheck();            } catch (RuntimeException e) {                System.out.println("No empty check: rider crashed with " + e);            }        }, "rider");        rider.start();        rider.join();    }}
Output
No full check:  most bags on the shelf at once = 8 (capacity 3)
No empty check: rider crashed with java.util.NoSuchElementException

What this code does

  • Without the full check, a fast producer simply keeps adding. The "bounded" buffer grows to 8 bags, and with a real stream of orders it would grow until memory runs out.
  • Without the empty check, a consumer that arrives first calls remove() on an empty queue and crashes with NoSuchElementException. Each side needs its own guard: producers wait while full, consumers wait while empty.

Two producers and two consumers

With several producers and several consumers, every rule from the last two lessons matters at once. Producers and consumers wait on the same object for different conditions, so notifyAll() is needed. Several consumers race for one item, so each must recheck in a while loop.

Example 4 · Two warehouses and two riders

TwoAndTwoDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Queue;
class SharedShelf {    private final Queue<String> items = new ArrayDeque<>();    private final int capacity;    private final List<String> takenOrder = new ArrayList<>();   // every take, in order
    SharedShelf(int capacity) {        this.capacity = capacity;    }
    synchronized void put(String item) throws InterruptedException {        while (items.size() == capacity) {            wait();        }        items.add(item);        notifyAll();    }
    synchronized String take() throws InterruptedException {        while (items.isEmpty()) {            wait();        }        String item = items.remove();        takenOrder.add(item);        notifyAll();        return item;    }
    synchronized List<String> takenOrder() {        return new ArrayList<>(takenOrder);    }}
public class TwoAndTwoDemo {    public static void main(String[] args) throws InterruptedException {        SharedShelf shelf = new SharedShelf(3);        List<Thread> threads = new ArrayList<>();
        for (String warehouse : new String[] {"D", "B"}) {          // Delhi warehouse, Bengaluru warehouse            threads.add(new Thread(() -> {                try {                    for (int i = 1; i <= 5; i++) {                        shelf.put(warehouse + "-" + i);                    }                } catch (InterruptedException e) {                    return;                }            }, "warehouse-" + warehouse));        }        for (int r = 1; r <= 2; r++) {            threads.add(new Thread(() -> {                try {                    for (int i = 0; i < 5; i++) {                 // each rider takes 5 bags                        shelf.take();                    }                } catch (InterruptedException e) {                    return;                }            }, "rider-" + r));        }        for (Thread t : threads) {            t.start();        }        for (Thread t : threads) {            t.join();        }
        List<String> taken = shelf.takenOrder();        List<String> delhiOrder = new ArrayList<>();        for (String s : taken) {            if (s.startsWith("D-")) {                delhiOrder.add(s);            }        }        List<String> sorted = new ArrayList<>(taken);        Collections.sort(sorted);        System.out.println("Taken: " + sorted.size() + " bags, all different: " + (sorted.stream().distinct().count() == 10));        System.out.println("Sorted: " + sorted);        System.out.println("Delhi warehouse bags left in order: " + delhiOrder);    }}
Output
Taken: 10 bags, all different: true
Sorted: [B-1, B-2, B-3, B-4, B-5, D-1, D-2, D-3, D-4, D-5]
Delhi warehouse bags left in order: [D-1, D-2, D-3, D-4, D-5]

What this code does

  • Four threads share one wait set: warehouses waiting for "not full" and riders waiting for "not empty". That is exactly the mixed-waiters case where notify() can wake the wrong kind and hang; notifyAll() plus while is always safe.
  • How the bags interleave and which rider takes which bag change from run to run, so the program prints only facts that are always true: 10 bags, no duplicates, and each warehouse's bags leave the shelf in the order they were made.

The interleaving changes on every run. Check results that must always hold, such as "every item taken exactly once" and "each producer's items stay in order", not one particular order of lines.

Make items and use them outside the lock. Only the put and take calls need to be synchronized.

Tracing the buffer step by step

To understand a bounded buffer, follow its contents one event at a time. With capacity 2, a fast warehouse and a slow rider, the pattern repeats.

Example 5 · Tracing a buffer of capacity 2

BufferTraceDemo.javaJava
import java.util.ArrayDeque;import java.util.Queue;
class TracedBuffer {    private final Queue<String> items = new ArrayDeque<>();    private final int capacity = 2;
    synchronized void put(String item) throws InterruptedException {        while (items.size() == capacity) {            System.out.println("  warehouse waits: shelf full " + items);            wait();        }        items.add(item);        System.out.println("put  " + item + "  shelf " + items);        notifyAll();    }
    synchronized String take() throws InterruptedException {        while (items.isEmpty()) {            System.out.println("  rider waits: shelf empty");            wait();        }        String item = items.remove();        System.out.println("take " + item + "  shelf " + items);        notifyAll();        return item;    }}
public class BufferTraceDemo {    public static void main(String[] args) throws InterruptedException {        TracedBuffer shelf = new TracedBuffer();        Thread warehouse = new Thread(() -> {            try {                for (String bag : new String[] {"A", "B", "C", "D"}) {                    shelf.put(bag);                }            } catch (InterruptedException e) {                return;            }        }, "warehouse");        Thread rider = new Thread(() -> {            try {                Thread.sleep(100);                  // the rider arrives late                for (int i = 0; i < 4; i++) {                    shelf.take();                    Thread.sleep(50);               // delivering, outside the lock                }            } catch (InterruptedException e) {                return;            }        }, "rider");        warehouse.start();        rider.start();        warehouse.join();        rider.join();    }}
Sample output
put  A  shelf [A]
put  B  shelf [A, B]
  warehouse waits: shelf full [A, B]
take A  shelf [B]
put  C  shelf [B, C]
  warehouse waits: shelf full [B, C]
take B  shelf [C]
put  D  shelf [C, D]
take C  shelf [D]
take D  shelf []

What this code does

  • Every line is printed inside the lock, so the lines show the true order of events. The warehouse fills the shelf with A and B and waits. Each take frees one place and wakes the warehouse, which adds one bag and fills the shelf again.
  • After D the warehouse is done, and the rider empties the shelf. The rider never waits here because it is always slower than the warehouse. On a very busy machine the timing can shift and a few lines can swap, so the output is labelled a sample.
  • The warehouse adds bags until the shelf is full, then waits.
  • The rider takes one bag, making one free place, and calls notifyAll().
  • The warehouse wakes, adds one bag and fills the shelf again.
  • When the warehouse is done, the rider empties the shelf. With a slow warehouse, the roles flip: the rider waits on an empty shelf.

Trace the code

Follow a shelf that holds only two bags

Step through five events on a shelf with room for 2 bags.

import java.util.ArrayDeque;
import java.util.Deque;
public class ShelfTrace {
public static void main(String[] args) {
Deque<String> shelf = new ArrayDeque<>();
int capacity = 2;
String[] events = {"put A", "put B", "put C", "take", "put C"};
for (String e : events) {
if (e.equals("take")) {
System.out.println(e + " " + shelf.removeFirst() + " -> " + shelf);
} else if (shelf.size() == capacity) {
System.out.println(e + " must wait: shelf full " + shelf);
} else {
shelf.addLast(e.substring(4));
System.out.println(e + " -> " + shelf);
}
}
}
}

Variables

e
put A
shelf
[]

Output

(nothing printed yet)

Line 9The next event is "put A".

Step 1 of 13

Next step

Check your understanding

12 quick questions