Quick revision
The short answer
Use a bounded ArrayBlockingQueue between one producer thread and four consumer threads: the producer calls put(), which blocks when the queue is full, and each consumer calls take(), which blocks when it is empty. To stop cleanly, the producer puts one poison pill, a special marker object, per consumer after the last line, and each consumer exits when it takes one. Alternatively, the executor can be shut down with interrupts and consumers exit on InterruptedException; either way, each record is processed inside a try/catch so one bad line does not stop the whole pipeline.
What to remember
In this answer, we built a producer-consumer pipeline with one producer thread reading a file and four consumers. A bounded ArrayBlockingQueue gives backpressure, because put() blocks when it is full and take() blocks when it is empty. The producer stops the consumers by putting one poison pill per consumer after the last line, in a finally block, so every line is processed before they exit. Interrupts through shutdownNow() are the alternative for aborting, and a try/catch around each record keeps one bad line from stopping the whole pipeline.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Use a bounded ArrayBlockingQueue between one producer thread and four consumer threads: the producer calls put(), which blocks when the queue is full, and each consumer calls take(), which blocks when it is empty. To stop cleanly, the producer puts one poison pill, a special marker object, per consumer after the last line, and each consumer exits when it takes one. Alternatively, the executor can be shut down with interrupts and consumers exit on InterruptedException; either way, each record is processed inside a try/catch so one bad line does not stop the whole pipeline.
Why this question is asked
Producer-consumer is the most practical concurrency pattern there is: a file importer, a log shipper, a crawler and a batch job all have one side that creates work and another that processes it. Java's BlockingQueue makes the core easy, so interviewers focus on the parts that are easy to get wrong: memory limits, how consumers know the work is finished, and what happens when a record fails. In this answer, we will recap the pattern and BlockingQueue, write the producer and consumers, explain why the queue is bounded, stop the consumers with poison pills, look at the interrupt-based alternative, and handle failures.
1A Quick Recap of Producer-Consumer
In the producer-consumer pattern, one or more producers put work items into a shared buffer and one or more consumers take items out and process them. The buffer decouples their speeds: reading lines from a file is fast, while processing each line, perhaps parsing and writing to a database, is slower, so we run several consumers in parallel.
A BlockingQueue is a thread-safe queue whose operations can wait. put(item) adds an item and, if the queue is full, blocks the calling thread until there is space. take() removes an item and, if the queue is empty, blocks until one arrives. With these two calls, threads coordinate without any explicit locks or wait/notify code.
2The Producer and the Four Consumers
Here is the whole program. A unique String instance serves as the poison pill, compared by identity with ==, so it can never be confused with a real line, even one that contains the same text.
Notice that the consumer is submitted as a Callable, because it returns null. A Callable may throw checked exceptions, so take() can throw InterruptedException without a try/catch inside the lambda. The main thread is the producer, and the try/finally guarantees that the pills are sent even if reading the file fails halfway, so the consumers never wait forever.
3Why the Queue Must Be Bounded
Reading a file can easily produce a million lines a second, while four consumers writing to a database might handle 20,000 a second. With an unbounded queue, such as a LinkedBlockingQueue created without a capacity, the producer would read the whole file into memory in a few seconds. For a 10 GB file, that is an OutOfMemoryError.
With ArrayBlockingQueue of capacity 1,000, the producer fills the queue and then blocks in put() until a consumer takes a line. The producer automatically slows to the consumers' speed, and memory holds at most 1,000 lines. This automatic slowing down is called backpressure, and the bounded queue gives it to us for free. The capacity is a tuning knob: large enough that consumers rarely find the queue empty while the producer is reading, small enough to bound memory.
4Stopping Cleanly With Poison Pills
The consumers cannot tell from an empty queue that the work is finished, because empty might just mean the producer is slow. They need an explicit signal that travels through the queue itself. That is the poison pill: a special item that means no more work. Because it goes through the same FIFO queue, it arrives after every real line the producer put before it, so no work is lost.
7 messages in order. Play them, or step through them one at a time.
Pills travel behind the real lines, so every line is processed before any consumer stops.
Why one pill per consumer? Each pill is taken by exactly one consumer, which then returns. With four consumers and one pill, the first consumer to take it would stop and the other three would block on take() forever, so awaitTermination would time out. Four pills stop four consumers. Another common style is for a consumer to put the pill back before it exits so the next consumer sees it too; that works with a single pill, but one pill per consumer is easier to reason about. If consumers might die before taking their pill, a full queue could block put(POISON), so production code often uses offer with a timeout for the pills.
5The Alternative: Shutting Down With Interrupts
Interrupts are Java's cooperative way to ask a thread to stop. Blocking methods such as take() respond to an interrupt by throwing InterruptedException. So instead of pills, the main thread can wait until the queue is empty and then call shutdownNow(), which interrupts every consumer thread.
This works, but notice its weakness: an empty queue does not mean the consumers have finished the lines they already took, and an interrupt can also arrive while a consumer is in the middle of process(line), perhaps inside a database call. Interrupts are therefore best for aborting, for example when the user cancels or the application shuts down, while poison pills are best for finishing normally.
6Handling Consumer Failures
The last requirement is resilience. If process(line) throws for a malformed line and nothing catches it, the exception ends the task, and that consumer is gone. With four consumers, four bad lines would silently stop all processing, while the producer blocks forever on a full queue. That is why the consumer wraps each record in its own try/catch, counts the failure, and keeps going. In real systems, failed records usually go to a dead-letter file or table with the error, so they can be inspected and replayed, and the job reports both counts at the end. Errors that are not about one record, such as the database being down, should instead stop the job, otherwise every remaining line fails one by one.
7Follow-up questions
Why not use a parallel stream over Files.lines()?
For simple CPU-bound processing, a parallel stream is shorter. But it gives little control over the number of threads, runs on the common ForkJoinPool which is a poor place for blocking database calls, and provides no backpressure or per-record failure handling. The explicit queue makes these choices visible.
Could the consumers be virtual threads?
Yes. On Java 21 and later, Executors.newVirtualThreadPerTaskExecutor() can run the consumers, and blocking in take() or in database calls is cheap for virtual threads. The design does not change: the bounded queue and the poison pills still do the same jobs. Virtual threads matter more when we want many more consumers than four.
How do you choose the number of consumers?
Measure. Start with a number based on what the consumers wait for: for database writes, roughly the number of connections the pool can give us; for CPU work, the number of cores. Then watch throughput and queue depth: if the queue is always full, consumers are the bottleneck and more may help, until the database itself saturates.
8Conclusion
In this answer, we built a producer-consumer pipeline with one producer thread reading a file and four consumers. A bounded ArrayBlockingQueue gives backpressure, because put() blocks when it is full and take() blocks when it is empty. The producer stops the consumers by putting one poison pill per consumer after the last line, in a finally block, so every line is processed before they exit. Interrupts through shutdownNow() are the alternative for aborting, and a try/catch around each record keeps one bad line from stopping the whole pipeline.
Open with
I would use an ArrayBlockingQueue with a fixed capacity, say a thousand lines, between the producer and four consumers running in an executor. The producer reads the file line by line and calls put, which blocks when the queue is full, so it can never read the whole file into memory; that gives backpressure for free.
Then, if they want more
Each consumer loops on take, which blocks while the queue is empty. For a clean stop, the consumers cannot use an empty queue as the signal, because empty might just mean the producer is slow.
So after the last line, the producer puts a poison pill, a unique marker object, once per consumer, in a finally block so it happens even if reading fails. Because the queue is FIFO, the pills arrive after all real lines, and each consumer returns when it takes one. One pill per consumer, otherwise three of them would wait forever.
Then I call shutdown and awaitTermination. The alternative is shutdownNow, which interrupts the consumers blocked in take, and they handle InterruptedException by restoring the flag and exiting, but that is better for aborting because it can cut work in progress.
Finally, each record is processed in its own try/catch that counts and logs failures, maybe to a dead-letter file, so one malformed line does not kill a consumer.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement producer-consumer with a BlockingQueue where one producer reads lines from a...": https://scrivio-interview-library.netlify.app/java/concurrency-patterns/71d93ff0a7/