invokeAll Blocking Behavior
What you'll learn: How invokeAll waits for all submitted tasks to finish before returning control to your code.
When you call invokeAll on an ExecutorService, it doesn't just fire off tasks and immediately return—it blocks the calling thread until all the submitted Callable tasks have completed (or until a timeout expires, if you specified one).
Understanding the Blocking Nature
Think of invokeAll like a project manager who refuses to leave a meeting until every team member has finished their report. The manager sits there, waiting, until the last person is done. Only then does the meeting end and everyone moves forward.
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Callable<Integer>> tasks = List.of(
() -> { Thread.sleep(1000); return 10; },
() -> { Thread.sleep(2000); return 20; },
() -> { Thread.sleep(500); return 30; }
);
System.out.println("Calling invokeAll...");
List<Future<Integer>> futures = executor.invokeAll(tasks);
System.out.println("All tasks completed!"); // Only prints after ~2000ms
In this example, even though the third task finishes in 500ms, invokeAll waits the full ~2000ms for the slowest task to complete before returning.
Why This Matters for Batch Processing
This blocking behavior makes invokeAll ideal for batch processing scenarios where you need all results before proceeding. You don't have to manually loop through futures calling get()—invokeAll guarantees that when control returns, all tasks are done (successfully or with exceptions).
The timeout variant—invokeAll(tasks, timeout, unit)—works similarly but will return after the timeout expires, cancelling any incomplete tasks.
Key Takeaway:
invokeAll blocks the calling thread until all submitted tasks complete (or timeout), making it perfect for batch operations where you need synchronized completion.