invokeAll with Timeout
What You'll Learn
You'll learn how to use the timeout variant of invokeAll to prevent indefinite waiting, automatically cancelling tasks that don't finish in time.
The Problem with Unbounded Waiting
In the previous lesson, you saw invokeAll block until all tasks complete. But what if one task hangs or takes unexpectedly long? Your application could freeze indefinitely waiting for that one problematic task.
The Timeout Variant
ExecutorService provides an overloaded version of invokeAll that accepts a timeout:
List<Future<V>> invokeAll(Collection<? extends Callable<V>> tasks,
long timeout, TimeUnit unit)
This method works like the standard invokeAll, but with a critical difference: if the timeout expires before all tasks complete, the method returns immediately and cancels any tasks still running.
How It Works
Think of it like a teacher giving students an exam with a strict time limit. When time's up, the teacher collects all papers—even incomplete ones—and no one can continue working.
List<Callable<String>> tasks = List.of(
() -> { Thread.sleep(100); return "fast"; },
() -> { Thread.sleep(5000); return "slow"; }
);
// Give tasks 1 second maximum
List<Future<String>> results =
executor.invokeAll(tasks, 1, TimeUnit.SECONDS);
// results.get(0).get() → "fast" (completed)
// results.get(1).isCancelled() → true (timed out)
The method returns a Future for every submitted task. Completed tasks have results available; cancelled tasks return true from isCancelled() and throw CancellationException if you call get().
When to Use This
Use the timeout variant when you need responsiveness guarantees and can tolerate incomplete results—like parallel web scraping where some sites may be slow or unresponsive.
Key Takeaway: The invokeAll timeout variant enforces a maximum wait time, automatically cancelling any tasks that don't complete within the deadline, giving you predictable blocking behavior.