Practical Pattern: Submitting Multiple Tasks and Collecting Results
What you'll learn: How to submit many tasks to an executor, collect all their Future objects, and gather results efficiently.
The Common Scenario
In real applications, you often need to execute multiple independent tasks concurrently—like fetching data from several APIs, processing files in parallel, or running computations across datasets. The pattern is straightforward: submit all tasks, collect their Future objects, then retrieve all results.
The Pattern in Action
ExecutorService executor = Executors.newFixedThreadPool(4);
List<Future<Integer>> futures = new ArrayList<>();
// Submit multiple Callable tasks
for (int i = 1; i <= 10; i++) {
final int taskId = i;
Callable<Integer> task = () -> {
Thread.sleep(1000); // Simulate work
return taskId * taskId; // Return square
};
futures.add(executor.submit(task));
}
// Collect all results
List<Integer> results = new ArrayList<>();
for (Future<Integer> future : futures) {
try {
results.add(future.get()); // Blocks until each completes
} catch (InterruptedException | ExecutionException e) {
System.err.println("Task failed: " + e.getMessage());
}
}
System.out.println("Results: " + results);
executor.shutdown();
How It Works
- Submit phase: Loop through your tasks, calling
submit()for each and storing the returnedFuturein a collection - Collection phase: Iterate through all
Futureobjects, callingget()to retrieve each result - Error handling: Wrap
get()in try-catch to handle failures gracefully
The beauty: tasks run concurrently (limited by pool size), but you can conveniently collect all results in order.
Key Takeaway: The submit-collect-gather pattern lets you parallelize multiple independent tasks easily: submit all tasks first (collecting Futures), then iterate through futures calling get() to assemble results, handling exceptions as needed.