Producer-Consumer Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Producer-Consumer Pattern runs in O(1) per op time and O(n) space, in Java as in every other language.
- ✓BlockingQueue<E> in java.util.concurrent is the interface, with put and take blocking and offer and poll supporting timeouts.
- ✓Use ArrayBlockingQueue with an explicit capacity so the bound cannot be forgotten. Shut down with a poison-pill object put once per consumer, or by interrupting the consumer threads, and if you catch InterruptedException, either rethrow it or restore the flag with Thread.currentThread().interrupt(), because swallowing it breaks every cancellation mechanism above you.
- ✓The Java trap: Executors.newFixedThreadPool hands its executor an UNBOUNDED LinkedBlockingQueue, so a fixed pool under sustained overload does not reject work or apply backpressure, it queues until it throws OutOfMemoryError.
- ✓ArrayBlockingQueue uses one lock for both ends, which is simple and predictable but serialises producers against consumers; LinkedBlockingQueue uses separate put and take locks and therefore achieves higher throughput under heavy two-sided contention, at the cost of a node allocation per element.
What Producer-Consumer Pattern actually is
Producer-Consumer Pattern in Java: what you actually reach for
Java implementation
import java.util.concurrent.*;
public final class Pipeline {
private static final Object POISON = new Object();
public static void run(int workers, int capacity) throws InterruptedException {
// BOUNDED by construction. LinkedBlockingQueue defaults to unbounded.
BlockingQueue<Object> queue = new ArrayBlockingQueue<>(capacity);
// Java 21+: a virtual thread per task; blocking take() is nearly free.
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < workers; i++) {
pool.submit(() -> {
try {
while (true) {
Object item = queue.take();
if (item == POISON) return null;
handle(item);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // NEVER swallow
return null;
}
});
}
for (int i = 0; i < 10_000; i++) queue.put(i); // blocks = backpressure
for (int i = 0; i < workers; i++) queue.put(POISON);
}
}
private static void handle(Object item) { }
// Executors.newFixedThreadPool uses an UNBOUNDED queue: under sustained
// overload it does not push back, it throws OutOfMemoryError. Construct
// ThreadPoolExecutor directly with a bounded queue + CallerRunsPolicy.
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1) per op
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Producer-Consumer Pattern?
BlockingQueue<E> in java.util.concurrent is the interface, with put and take blocking and offer and poll supporting timeouts. ArrayBlockingQueue(capacity) is bounded by construction; LinkedBlockingQueue is optionally bounded and UNBOUNDED by default. SynchronousQueue is a zero-capacity handoff, and ThreadPoolExecutor is itself a producer-consumer engine you can hand any of these queues.
What is the most common Java mistake when implementing Producer-Consumer Pattern?
Executors.newFixedThreadPool hands its executor an UNBOUNDED LinkedBlockingQueue, so a fixed pool under sustained overload does not reject work or apply backpressure, it queues until it throws OutOfMemoryError. This is the single most common way a Java service dies under load, and the fix is to construct ThreadPoolExecutor directly with a bounded queue and an explicit RejectedExecutionHandler such as CallerRunsPolicy, which pushes back on the producer by making it do the work. Related, Executors.newCachedThreadPool creates unbounded THREADS instead.
How does Producer-Consumer Pattern actually perform in Java?
ArrayBlockingQueue uses one lock for both ends, which is simple and predictable but serialises producers against consumers; LinkedBlockingQueue uses separate put and take locks and therefore achieves higher throughput under heavy two-sided contention, at the cost of a node allocation per element. SynchronousQueue is fastest for direct handoff when consumers keep up. Virtual threads make blocking on take nearly free, changing the calculus that made large pools necessary. Time complexity is O(1) per op and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.