1. How to coordinate multiple threads when processing files
When you work with large files or complex data processing, you often face a task: split the work across multiple threads. For example, one thread reads lines from a file, and others process those lines (search for words, compute statistics, etc.).
What’s the problem?
- If all threads work with the same resource (for example, a file or a shared collection), it’s easy to run into errors: some threads may “outrun” others, causing races, data loss, and memory overload.
- If there are many threads but no coordination, some will idle while others get overloaded.
You need a solution that:
- Allows safe data exchange between threads.
- Prevents memory overflow (if processing is slower than reading).
- Makes it easy to shut down all threads when the data is finished.
2. The “Producer–Consumer” pattern
Producer–Consumer is a classic pattern that helps threads work in harmony without stepping on each other’s toes.
It has two roles: the Producer creates data — for example, reads lines from a file or receives messages over the network — and puts them into a shared queue. The Consumer takes data from this queue and processes it: counts words, saves to a database, or writes to another file.
The main idea is that these two types of threads work independently. The producer can read faster than the consumer can process, or vice versa — and nobody blocks. Between them is a buffer — a queue that evens out the pace.
Visual diagram
[File] --(reads)--> [Producer] --(puts into queue)--> [BlockingQueue] --(takes)--> [Consumer] --(processes)
3. Implementation with BlockingQueue
In Java, the BlockingQueue interface (for example, the ArrayBlockingQueue implementation) is perfect for organizing such exchange.
What is a BlockingQueue?
A BlockingQueue is a thread-safe queue with a bounded capacity that takes care of synchronization for you. If a producer tries to add an element when the queue is full, the thread automatically blocks and waits until space becomes available. Similarly, if a consumer tries to take an element when the queue is empty, it simply waits until someone puts something into the queue.
This mechanism automatically solves the classic problems of thread “racing” and memory overflow: producers don’t flood the queue with extra elements, and consumers don’t try to work with nothing. All threads calmly and coherently do their job.
Example of creating a queue
import java.util.concurrent.*;
BlockingQueue<String> queue = new ArrayBlockingQueue<>(100); // buffer for 100 elements
100 is the maximum number of elements in the queue. If the producer runs faster, it will wait until the consumer processes some data.
4. Thread coordination: backpressure and shutdown
Limiting queue size (backpressure)
Backpressure is a mechanism that prevents the producer from “flooding” all memory if the consumer can’t keep up.
- If the queue is full, the producer automatically “slows down” (the put() method blocks).
- If the queue is empty, the consumer waits (the take() method blocks).
This allows the system to remain stable even when thread speeds differ.
Shutting down: the “poison pill”
When the producer finishes reading the file, it needs to inform the consumers that there will be no more data and it’s time to stop.
Solution:
- Put a special object into the queue — a “poison pill” (for example, the string "__END__" or another sentinel value, but not null).
- When a consumer gets the “poison pill,” it knows to terminate.
If there are multiple consumers, you must put as many “poison pills” as there are consumers!
5. Example pipeline: reading a file and processing lines
Let’s implement a simple pipeline:
- One thread reads lines from a file and puts them into the queue.
- Several threads take lines from the queue, count the number of words, and print the result.
Step 1. Producer — file reader
import java.io.*;
import java.util.concurrent.*;
public class FileProducer implements Runnable {
private final BlockingQueue<String> queue;
private final File file;
private final int consumerCount;
private final String POISON_PILL = "__END__";
public FileProducer(BlockingQueue<String> queue, File file, int consumerCount) {
this.queue = queue;
this.file = file;
this.consumerCount = consumerCount;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
queue.put(line); // if the queue is full — wait
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Put a poison pill for each consumer
try {
for (int i = 0; i < consumerCount; i++) {
queue.put(POISON_PILL);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Step 2. Consumer — line processor
import java.util.concurrent.BlockingQueue;
public class LineConsumer implements Runnable {
private final BlockingQueue<String> queue;
private final String POISON_PILL = "__END__";
public LineConsumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
String line = queue.take(); // if the queue is empty — wait
if (POISON_PILL.equals(line)) {
break; // termination
}
int wordCount = line.trim().isEmpty() ? 0 : line.trim().split("\\s+").length;
System.out.println(Thread.currentThread().getName() + ": " + wordCount + " words in line: " + line);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Step 3. Launching the pipeline via Executors
import java.io.File;
import java.util.concurrent.*;
public class PipelineDemo {
public static void main(String[] args) throws Exception {
int consumerCount = 3;
BlockingQueue<String> queue = new ArrayBlockingQueue<>(100);
File file = new File("input.txt"); // your file
// Start producer
Thread producer = new Thread(new FileProducer(queue, file, consumerCount));
producer.start();
// Start consumers via ExecutorService
ExecutorService consumers = Executors.newFixedThreadPool(consumerCount);
for (int i = 0; i < consumerCount; i++) {
consumers.submit(new LineConsumer(queue));
}
// Wait for producer to finish
producer.join();
// Wait for consumers to finish
consumers.shutdown();
consumers.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Processing completed!");
}
}
6. Visualization: pipeline workflow diagram
flowchart LR
A[Producer: reads file] -- put() --> Q[BlockingQueue]
Q -- take() --> C1[Consumer 1: counts words]
Q -- take() --> C2[Consumer 2: counts words]
Q -- take() --> C3[Consumer 3: counts words]
A -.->|poison pill| Q
Q -.->|poison pill| C1
Q -.->|poison pill| C2
Q -.->|poison pill| C3
7. Useful nuances and best practices
- Limit the queue size — this protects against memory overflow.
- Use a “poison pill” for shutdown — otherwise consumers may hang forever.
- Do not use null as a “poison pill” if real null values may appear in the queue. Prefer a special string or object.
- Handle InterruptedException — it’s important for graceful thread termination.
- Use ExecutorService to manage the thread pool — it’s simpler and safer than creating threads manually.
8. Typical mistakes when implementing a pipeline
Error #1: Unbounded queue → OutOfMemoryError. If you use a LinkedBlockingQueue without a size limit, the producer can flood all memory if the consumer can’t keep up.
Error #2: No “poison pill” → consumers get stuck. If you forget to put the “poison pills,” consumer threads will wait for new data forever.
Error #3: Only one “poison pill” while there are multiple consumers. Each consumer thread needs its own “poison pill,” otherwise not all of them will terminate.
Error #4: Not handling InterruptedException. If a thread is interrupted, you should finish gracefully (restore the interrupt flag), otherwise threads may “hang.”
Error #5: Sharing a variable between threads without synchronization. Don’t try to reinvent the wheel — use a BlockingQueue rather than plain lists or arrays.
GO TO FULL VERSION