Common join Patterns: Scatter-Gather
What You'll Learn
You'll learn how to implement the scatter-gather concurrency pattern using threads and the join() method to parallelize work and aggregate results.
The Scatter-Gather Pattern
The scatter-gather pattern is one of the most common uses of join() in concurrent programming. The idea is simple:
- Scatter: Launch multiple threads to work on independent tasks simultaneously
- Gather: Use
join()to wait for all threads to complete before processing their collective results
Think of it like a team of researchers gathering data from different sources. Each researcher works independently (scatter), but you can't write the final report until everyone returns with their findings (gather).
How It Works in Java
The pattern typically follows this structure:
- Create multiple threads, each performing a distinct computation or I/O operation
- Start all threads (scatter phase)
- Call
join()on each thread in sequence (gather phase) - Process the combined results
// Scatter: start independent tasks
Thread worker1 = new Thread(() -> {
// compute result 1
});
Thread worker2 = new Thread(() -> {
// compute result 2
});
Thread worker3 = new Thread(() -> {
// compute result 3
});
worker1.start();
worker2.start();
worker3.start();
// Gather: wait for all to complete
worker1.join();
worker2.join();
worker3.join();
// Now process all results
The order of join() calls doesn't matter for correctness—you'll wait for all threads regardless—but joining in creation order is a common convention.
Key Takeaway: The scatter-gather pattern uses join() to parallelize independent tasks and synchronize before aggregating their results, making it ideal for divide-and-conquer problems where subtasks can execute concurrently.