Java Concurrency Program · OT64
Producer-Consumer Problem in Java
The producer must wait when the buffer is full, and the consumer must wait when it is empty. A blocking queue does both waits for you.
Problem Statement
A producer thread creates the numbers 1 to 10 and a consumer thread processes them, through a buffer that holds at most 3 items.
No item may be lost or processed twice, and the consumer must stop cleanly when the producer is finished.
Input/Output Examples
produce 1 to 10, capacity 3Outputconsumed [1, …, 10]Explanation: in order, none missing.producer is fasterOutputput() blocksExplanation: it waits until the consumer takes an item.a poison value -1 is sent lastOutputconsumer exitsExplanation: a clean shutdown signal.Visual Explanation
- Fillbuffer123full: producer blocks
- take()buffer234consumer takes 1, producer adds 4
- Poisonbuffer-1after 10, -1 is put
- Doneconsumed 1..10, sum 55
take() makes room, and a final poison value tells the consumer to stop.Blocking puts the waiting thread to sleep instead of letting it spin. The poison value avoids having to interrupt the consumer.
Approaches
Both approaches use the same producer and consumer. One relies on ArrayBlockingQueue; the other implements the buffer by hand.
Approach 1: ArrayBlockingQueue (Recommended)
Idea: use a bounded ArrayBlockingQueue: put() blocks when it is full and take() blocks when it is empty.
- Create the queue with capacity 3.
- The producer calls
put(i)for 1 to 10, thenput(POISON). - The consumer calls
take()until it receivesPOISON.
Time: O(n) · Space: O(capacity).
Approach 2: wait() and notifyAll() Buffer
Idea: a synchronized buffer waits in a loop while full or empty and calls notifyAll() after every change.
put(): wait whilesize == capacity, add, then notify.take(): wait while empty, remove, then notify.- Use the same poison value to stop the consumer.
Time: O(n) · Space: O(capacity).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. The consumer records what it takes, and the results are printed only after both threads have finished, so the output is identical on every run (checked over 25 runs).
Approach 1: ArrayBlockingQueue (Recommended)
The standard production answer: all the waiting and signalling is inside the JDK class.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumerQueue {
private static final int POISON = -1; // tells the consumer to stop
// put() blocks when the buffer is full; take() blocks when it is empty
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(3);
List<Integer> consumed = new ArrayList<>();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
buffer.put(i);
}
buffer.put(POISON);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
while (true) {
int item = buffer.take();
if (item == POISON) {
break;
}
consumed.add(item);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("buffer capacity: 3");
System.out.println("consumed in order: " + consumed);
System.out.println("sum: " + consumed.stream().mapToInt(Integer::intValue).sum());
}
}
buffer capacity: 3 consumed in order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum: 55
Time complexity: O(n) · Space complexity: O(capacity).
Approach 2: wait() and notifyAll() Buffer
Shows what the blocking queue does internally, which is a common follow-up question.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class ProducerConsumerWaitNotify {
// A hand-written bounded buffer: wait() while full or empty, notifyAll() after every change
static class BoundedBuffer {
private final Deque<Integer> items = new ArrayDeque<>();
private final int capacity;
BoundedBuffer(int capacity) {
this.capacity = capacity;
}
synchronized void put(int x) throws InterruptedException {
while (items.size() == capacity) {
wait();
}
items.addLast(x);
notifyAll();
}
synchronized int take() throws InterruptedException {
while (items.isEmpty()) {
wait();
}
int x = items.removeFirst();
notifyAll();
return x;
}
}
private static final int POISON = -1;
public static void main(String[] args) throws InterruptedException {
BoundedBuffer buffer = new BoundedBuffer(3);
List<Integer> consumed = new ArrayList<>();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
buffer.put(i);
}
buffer.put(POISON);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
while (true) {
int item = buffer.take();
if (item == POISON) {
break;
}
consumed.add(item);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("buffer capacity: 3");
System.out.println("consumed in order: " + consumed);
System.out.println("sum: " + consumed.stream().mapToInt(Integer::intValue).sum());
}
}
buffer capacity: 3 consumed in order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum: 55
Time complexity: O(n) · Space complexity: O(capacity).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| ArrayBlockingQueue | O(n) | O(capacity) |
| wait() and notifyAll() Buffer | O(n) | O(capacity) |
Here n is the number of items. Each item is put and taken once; the buffer never holds more than its capacity.
Interview Tips and Recommended Approach
- Prefer
BlockingQueuein real code; it is correct and well tested. - Wait in a loop in hand-written buffers.
- Plan shutdown. A poison value, or interrupting the consumer, ends it cleanly.
- Scale out. With several consumers, send one poison value per consumer.
Recommended Approach: ArrayBlockingQueue
Why: it delegates all synchronisation to a tested JDK class, leaving only the producer and consumer logic in your code.