Course contentsShow
← Java
Lesson 2758 of 2,87050. Executor FrameworkFree lesson

invokeAll: Executing Multiple Callables

Learn how invokeAll submits a collection of Callable tasks and waits for all to complete, returning a list of Future objects.

invokeAll: Executing Multiple Callables

You'll learn how to submit multiple tasks at once and wait for all of them to finish, getting back a complete list of results.

The Need for Batch Submission

When you have multiple Callable tasks to execute, you could submit them individually with submit() and collect the Future objects yourself. But this is tedious and error-prone. The invokeAll method provides a cleaner, more convenient alternative.

How invokeAll Works

ExecutorService.invokeAll(Collection<? extends Callable<T>> tasks) accepts a collection of Callable tasks, submits them all for execution, and blocks until every single task completes (either successfully, with an exception, or by cancellation). It returns a List<Future<T>> where each Future corresponds to one of the input tasks, in the same order.

ExecutorService executor = Executors.newFixedThreadPool(3);

List<Callable<String>> tasks = List.of(
    () -> { Thread.sleep(1000); return "Task 1"; },
    () -> { Thread.sleep(500); return "Task 2"; },
    () -> { Thread.sleep(1500); return "Task 3"; }
);

List<Future<String>> futures = executor.invokeAll(tasks);
// This line blocks until ALL tasks complete

for (Future<String> future : futures) {
    String result = future.get(); // Will not block, already done
    System.out.println(result);
}

executor.shutdown();

Key Characteristics

  • Blocking: invokeAll doesn't return until all tasks finish
  • Order preserved: The returned list matches the input collection's order
  • Already done: After invokeAll returns, calling get() on any Future won't block (though it may throw ExecutionException)
  • Timeout variant: invokeAll(tasks, timeout, unit) cancels incomplete tasks after the timeout

Key Takeaway:
invokeAll submits a batch of Callable tasks, waits for all to complete, and returns a list of Future objects representing their results—perfect for parallel work that must all finish before proceeding.