Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a producer-consumer pair using a BlockingQueue where the producer reads lines from a file and two consumers process them, and the consumers stop cleanly when the file is done.

Use a bounded queue such as new ArrayBlockingQueue<String>(1000) so a slow consumer makes the producer wait. The producer puts each line, then puts one poison pill, a unique sentinel object, per consumer; each consumer loops on take and exits when it receives the sentinel. InterruptedException is handled by restoring the interrupt flag and exiting, and all three tasks run on an ExecutorService that we shut down and await.

Why this question is asked

Producer-consumer is the classic pattern for connecting work that happens at different speeds: reading a file is fast, processing each line may call a database or a service. The hard part is not moving data through the queue but stopping cleanly: consumers block in take, so they need a way to learn that no more data will come. Interviewers ask for this code because it tests bounded queues, shutdown signalling, interruption and executor handling in a few dozen lines. In this answer, we will recap the pattern, design the shutdown signal, write the full program, walk through what happens at the end of the file, and look at failure cases.

1A Quick Recap of the Pattern

One producer thread reads lines and puts them into a shared BlockingQueue. Two consumer threads take lines out and process them. The queue decouples the speeds: if consumers are briefly slow, lines wait in the queue; if they stay slow and the queue is bounded, the producer's put blocks until there is room. That is backpressure, and it keeps memory use fixed at about the capacity times the size of a line, whatever the file size.

If we used an unbounded queue instead, a fast producer reading a 20 GB file would load most of it into memory while the consumers fall behind. A capacity of 1,000 lines is a reasonable starting point: large enough to smooth out short pauses, small enough to bound memory.

2Designing the Stop Signal

Consumers call take, which blocks while the queue is empty. When the file ends, they must stop rather than wait forever. The standard technique is a poison pill: a special element that means no more data. The producer puts one pill per consumer after the last line, because each consumer exits after taking one pill; with two consumers and one pill, the second would wait forever.

The pill must be impossible to confuse with real data. A string such as "EOF" could appear in the file. So we create a unique object with new String("<end>") and compare by identity, with ==, not with equals. A line read from the file is always a different object, even if it has the same characters, so it can never match. In a typed design, a sealed interface with a Line record and an End marker expresses the same thing more explicitly.

Step throughEnd of file with two consumers
ProducerQueue (1000)Consumer 1Consumer 2
put(line 1) ... put(last line)
take(): lines, processed
take(): lines, processed
put(POISON) twice, one per consumer
take() returns POISON: exit loop
take() returns POISON: exit loop
producer task ends

7 messages in order. Play them, or step through them one at a time.

Each consumer stops after its own pill, so lines ahead of the pills are all processed first.

3The Full Program

Here is the complete program. The producer and both consumers run as tasks on one fixed thread pool.

Java
public class LinePipeline {
private static final String POISON = new String("<end>"); // unique object, compared with ==
private static final int CONSUMERS = 2;
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(1000); // bounded: backpressure
ExecutorService pool = Executors.newFixedThreadPool(CONSUMERS + 1);
pool.submit(() -> produce(Path.of(args[0]), queue));
for (int i = 0; i < CONSUMERS; i++) {
int id = i;
pool.submit(() -> consume(id, queue));
}
pool.shutdown(); // no new tasks; running ones continue
if (!pool.awaitTermination(1, TimeUnit.HOURS)) { // wait for all three to finish
pool.shutdownNow(); // interrupts them if they are stuck
}
}
static void produce(Path file, BlockingQueue<String> queue) {
try {
try (BufferedReader in = Files.newBufferedReader(file)) {
String line;
while ((line = in.readLine()) != null) {
queue.put(line); // blocks while 1000 lines are waiting
}
} catch (IOException e) {
System.err.println("read failed: " + e); // still stop the consumers below
}
for (int i = 0; i < CONSUMERS; i++) queue.put(POISON); // one pill per consumer
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and exit
}
}
static void consume(int id, BlockingQueue<String> queue) {
try {
while (true) {
String line = queue.take(); // blocks while the queue is empty
if (line == POISON) return; // identity check, not equals
try {
process(id, line);
} catch (RuntimeException e) {
System.err.println("line failed: " + e); // one bad line must not kill the consumer
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and exit
}
}
static void process(int id, String line) { /* parse, save, call a service ... */ }
}

Notice that the pills are put even when reading fails with an IOException, so consumers never wait for data that will not come. Notice too that a processing failure on one line is caught inside the loop: if a consumer died on an exception, the producer could block forever on a full queue with nobody taking from it.

4Why We Restore the Interrupt Flag

Interruption is Java's cooperative way of asking a thread to stop. Blocking methods such as put and take respond by throwing InterruptedException, and in doing so they clear the thread's interrupt flag. If we catch the exception and carry on, the request to stop is lost. Calling Thread.currentThread().interrupt() sets the flag again, so the executor or any code higher up can still see that the thread was asked to stop, and then we return from the task.

In our program, interruption happens when awaitTermination times out and shutdownNow interrupts all pool threads. Consumers blocked in take and a producer blocked in put each throw InterruptedException, restore the flag and exit, so the program ends instead of hanging.

5Shutting Down the Executor

shutdown tells the pool to accept no new tasks but to finish the ones already submitted. awaitTermination then waits until all of them have completed or the timeout expires, and returns true or false accordingly. Without awaitTermination, main would return while work is still running; without shutdown, the pool's non-daemon threads would keep the JVM alive after all tasks finished.

Since Java 19, ExecutorService implements AutoCloseable, so a try-with-resources block around the pool calls close, which shuts down and waits for tasks to complete. It is shorter, but it waits without a time limit, so the explicit shutdown and awaitTermination with a timeout is still useful when we want a bound. Since the consumers mostly wait on the queue or on I/O, virtual threads through Executors.newVirtualThreadPerTaskExecutor would work just as well.

6Follow-up questions

What if the number of consumers is not known to the producer?

Then a pill per consumer is hard to arrange. Alternatives are a single pill that each consumer puts back before exiting, so the next one sees it too, or a shared done flag combined with poll with a timeout, where consumers exit when the flag is set and the queue is empty. The re-put pill is the simplest and keeps the take loop.

Why not just interrupt the consumers when the file ends?

Interruption would stop them immediately, even if lines are still in the queue, so the last lines would be lost. The poison pill travels through the queue behind the data, so consumers process everything that was put before it and then stop.

How would you return results from the consumers?

Submit the consumers as Callable tasks that return, for example, the number of lines processed, keep the Future objects, and call get on each after awaitTermination. get also rethrows any exception the task ended with, wrapped in ExecutionException.

7Conclusion

In this answer, we built a producer-consumer pipeline with a bounded ArrayBlockingQueue of 1,000 lines, so slow consumers make the producer wait. The producer puts every line and then one unique poison pill per consumer, even after a read error, and each consumer loops on take and exits when it sees the pill by identity. InterruptedException restores the interrupt flag and exits, and the three tasks run on an ExecutorService that we shut down and await with a timeout, falling back to shutdownNow.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use a bounded queue, for example an ArrayBlockingQueue of strings with capacity 1000, so that if the consumers are slower than reading the file, the producer's put blocks and memory stays bounded.

Then, if they want more

The producer opens the file with a BufferedReader and puts each line. When it reaches the end, it puts one poison pill per consumer, so two pills here, because each consumer exits after taking exactly one.

The pill is a unique object, created with new String, and consumers compare it with double equals, by identity, so no real line from the file can ever match it. I also put the pills if reading fails, so consumers never wait forever.

Each consumer loops on take, returns when it gets the pill, and otherwise processes the line, catching runtime exceptions per line so one bad line does not kill the consumer and leave the producer blocked on a full queue. Both sides catch InterruptedException, call Thread.currentThread().interrupt() to restore the flag, and exit, because interruption means someone asked the task to stop.

I run the producer and the two consumers on an ExecutorService with three threads, then call shutdown so no new tasks are accepted, and awaitTermination with a timeout; if that times out I call shutdownNow, which interrupts the tasks, and they exit cleanly through the interrupt handling.

Since the pill travels behind the data, every line is processed before the consumers stop.

About this answer

Last updated
12 November 2026
Versions it names
Java 19
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "Write a producer-consumer pair using a BlockingQueue where the producer reads lines from...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/0bf99ccf3b/