Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Producer–Consumer and BlockingQueue

    The producer–consumer pattern: some threads produce work items, others consume them, connected by a queue. It decouples speeds and smooths bursts.

    Chapter 7 of 124 min read

    The Plain Picture#

    A bakery: bakers put loaves on a shelf that holds only 2. When the shelf is full, bakers wait. The shop assistant takes loaves off; when the shelf is empty, the assistant waits. Nobody has to keep asking "is there space yet?" — they're woken when something changes.

    The Real Names#

    • The producer–consumer pattern: some threads produce work items, others consume them, connected by a queue. It decouples speeds and smooths bursts.

    • A BlockingQueue is a thread-safe queue whose put waits when full and take waits when empty. Implementations: ArrayBlockingQueue (bounded, array-based), LinkedBlockingQueue (optionally bounded), PriorityBlockingQueue, DelayQueue, SynchronousQueue (a hand-off with no storage).

    • It's what's inside every thread pool (Ch 2) — the "order rail".

    • A special value like "DONE" that tells consumers to stop is called a poison pill.

    Under the Hood#

    Java
    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2); // shelf holds 2
    
    Thread producer = new Thread(() -> {
        for (String q : List.of("q1", "q2", "q3", "q4")) {
            queue.put(q);
            System.out.println("produced " + q);
        }
        queue.put("DONE"); // poison pill
    });
    
    Thread consumer = new Thread(() -> {
        while (true) {
            String q = queue.take();
            if (q.equals("DONE")) break;
            Thread.sleep(100); // slow consumer (e.g. calling the AI API)
            System.out.println("  consumed " + q);
        }
    });
    Output
    produced q1
    produced q2
    produced q3          ← the consumer took q1 off the shelf, making room
      consumed q1
    produced q4          ← had to WAIT for space: the producer is held back to the consumer's pace
      consumed q2
      consumed q3
      consumed q4

    The bounded queue gave backpressure automatically: the fast producer couldn't run ahead of the slow consumer by more than 2 items. The same pattern at the scale of whole systems is a message queue like Kafka or SQS (Background Jobs and Queues (coming soon)).

    The low-level version — wait() / notify() / notifyAll() on a monitor — is what BlockingQueue is built from, and interviewers sometimes ask you to write it. The two rules: call them only while holding the object's lock, and always wait in a while loop that re-checks the condition (threads can wake up without being notified — a "spurious wakeup" — or find the condition changed by another thread first):

    Java
    synchronized (lock) {
        while (queue.isEmpty()) lock.wait(); // while, not if
        item = queue.remove();
        lock.notifyAll(); // wake producers waiting for space
    }

    In real code, use BlockingQueue.

    Check yourself

    4 questions
    1

    What happens on put to a full ArrayBlockingQueue? On take from an empty one?

    Show answer

    put blocks until space is available; take blocks until an element arrives.

    2

    What is backpressure, and how did the bounded queue provide it?

    Show answer

    Slowing producers down to consumers' pace instead of letting work pile up; put blocked when the 2-item queue was full.

    3

    Why must wait() be called in a while loop?

    Show answer

    The thread can wake spuriously or another thread may have changed the condition, so it must re-check before proceeding.

    4

    What's a poison pill?

    Show answer

    A special item placed in the queue to tell consumers to stop.