Design Data Structures · Pattern 9 of 10

Concurrency: a bounded blocking queue

Producers wait while the queue is full and consumers wait while it is empty. One lock protects the queue, and a condition variable lets a thread sleep until another one changes the state.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Several threads add and remove items
  • A method must block (wait) until there is space or data
  • Producer and consumer, or a fixed pool of slots

The template

Concurrency
class BoundedBlockingQueue {
    private final Deque<Integer> q = new ArrayDeque<>();
    private final int capacity;
    BoundedBlockingQueue(int capacity) { this.capacity = capacity; }
    synchronized void enqueue(int element) throws InterruptedException {
        while (q.size() == capacity) wait();     // while, not if: re-check after waking
        q.addLast(element);
        notifyAll();                             // wake threads waiting for an item
    }
    synchronized int dequeue() throws InterruptedException {
        while (q.isEmpty()) wait();
        int x = q.pollFirst();
        notifyAll();                             // wake threads waiting for space
        return x;
    }
    synchronized int size() { return q.size(); }
}

The variations

  1. 1Lock plus condition: wait while you cannot proceed

    Take the lock, loop while (cannot proceed) wait(), change the queue, then notify the others. Waiting releases the lock so another thread can make progress. Java can also use a ReentrantLock with two conditions (notFull, notEmpty), or two semaphores counting free and used slots.

Mistakes to avoid

  • Waiting with if instead of while: a thread can wake up and find the condition false again (another thread got there first, or a spurious wake-up).
  • Calling notify (one thread) when producers and consumers share one condition: it may wake the wrong kind and everyone sleeps. Use notifyAll, or two separate conditions.
  • Reading size or the queue without holding the lock.
Next: Simulation designs: model the state directly →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.