Tech Interview RoomStudy guides

Concurrency

Implement producer-consumer with a bounded buffer, both with BlockingQueue and with wait/notify.

Intermediate · 2 min read · Lesson 1 of 5 in Concurrency

Problem

Producers create items and consumers process them through a buffer with a fixed capacity. Producers must block when the buffer is full and consumers when it is empty.

Approach 1: BlockingQueue (what you use in production)

ArrayBlockingQueue.put blocks when full and take blocks when empty. A "poison pill" tells consumers to stop.

Approach 2: your own bounded buffer with a lock and two conditions

Using ReentrantLock with separate notFull and notEmpty conditions avoids waking the wrong kind of thread. Always wait in a while loop to handle spurious wakeups.

java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class BoundedBuffer<T> {
    private final Deque<T> items = new ArrayDeque<>();
    private final int capacity;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    BoundedBuffer(int capacity) { this.capacity = capacity; }

    void put(T item) throws InterruptedException {
        lock.lock();
        try {
            while (items.size() == capacity) notFull.await();
            items.addLast(item);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    T take() throws InterruptedException {
        lock.lock();
        try {
            while (items.isEmpty()) notEmpty.await();
            T item = items.removeFirst();
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
}

class ProducerConsumerDemo {
    private static final int POISON = -1;

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 100; i++) queue.put(i);
                queue.put(POISON);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                long sum = 0;
                for (int v; (v = queue.take()) != POISON; ) sum += v;
                System.out.println("sum = " + sum);   // 5050
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
    }
}

Complexity

O(1) per put or take; memory bounded by the capacity, which gives natural back-pressure.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you stop several consumers cleanly?

Send one poison pill per consumer, or have a shared volatile boolean done flag plus poll(timeout) instead of take() so consumers re-check the flag periodically, or run consumers in an ExecutorService and call shutdownNow(), which interrupts blocked take() calls (they throw InterruptedException, and the consumer exits after restoring the interrupt flag).

Why use two Conditions instead of wait/notifyAll on one monitor?

With a single monitor, notify() might wake another producer when the buffer has just become full, and the signal is wasted (or threads stall); notifyAll() fixes it by waking everyone, at the cost of unnecessary context switches. Separate conditions let a producer signal exactly one waiting consumer and vice versa.