Sub topic 7
Running Many Tasks with `allOf` and `anyOf`
Assume you know Java lambdas, generics, CompletableFuture, and basic executor use. This chapter focuses on coordinating several asynchronous tasks after they have started.
When you have one asynchronous task, methods such as thenApply are enough to process its result. When you have many tasks, you often need one of two rules:
- Wait until every task finishes.
- Continue as soon as the first task finishes.
CompletableFuture.allOf implements the first rule. CompletableFuture.anyOf implements the second.
Waiting for every task with `allOf`
allOf accepts several futures and returns a new CompletableFuture<Void>. The returned future completes when all input futures complete.
It does not collect the results for you. You must keep the original futures and read their results after allOf finishes.
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ManyTasks {
static CompletableFuture<Integer> square(int number) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(number * 100L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return number * number;
});
}
public static void main(String[] args) {
List<CompletableFuture<Integer>> futures = IntStream.rangeClosed(1, 3)
.mapToObj(ManyTasks::square)
.collect(Collectors.toList());
CompletableFuture<Void> allDone = CompletableFuture.allOf(
futures.toArray(new CompletableFuture<?>[0])
);
List<Integer> results = allDone
.thenApply(ignored -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()))
.join();
System.out.println(results);
Object first = CompletableFuture.anyOf(
square(4),
square(1),
square(3)
).join();
System.out.println("First result: " + first);
}
}The first output is [1, 4, 9]. The list follows the order of futures, not the order in which tasks finish. The second output is usually First result: 1, because square(1) has the shortest delay.
join is safe inside the thenApply stage here because allDone has already completed. Calling join on each original future does not normally wait again. If any input future failed, however, its join throws a CompletionException.
Continuing with the first result using `anyOf`
anyOf also accepts several futures, but it completes when the first input future completes. “Completes” includes both success and failure.
Its return type is CompletableFuture<Object> because the input futures may have different result types:
CompletableFuture<Object> first = CompletableFuture.anyOf(
CompletableFuture.completedFuture("cached value"),
CompletableFuture.completedFuture(42)
);The caller must inspect or convert the Object value. If all participating futures have the same type, you can cast carefully, but a cast does not make the operation type-safe.
The first completed future wins. A slower future may continue running after anyOf has completed. anyOf does not automatically cancel the remaining tasks.
Failure behavior and result collection
allOf completes exceptionally if at least one input future fails. It does not stop the other tasks. They may continue running, and their failures may need separate logging or handling.
anyOf completes with the first completion, even when that completion is exceptional. A fast failure can therefore win a race before a slower successful task finishes.
You can attach error handling to the combined future:
CompletableFuture<Void> checked = CompletableFuture.allOf(
futures.toArray(new CompletableFuture<?>[0])
).exceptionally(error -> {
System.err.println("At least one task failed: " + error);
return null;
});The exception passed through these stages is often a CompletionException. Its cause contains the original exception. Use error.getCause() when you need to inspect that original failure.
Common mistakes
- Expecting
allOfto return a list. It returnsCompletableFuture<Void>. - Assuming result order equals completion order. The original future list controls collection order.
- Assuming
anyOfcancels losing tasks. It does not. - Ignoring exceptional completion. Both combinators propagate failure.
- Blocking a common-pool worker with unrelated long-running work. Use a suitable custom executor for blocking operations.
Exercise
You have five futures and need all five values in the same order as the input list. Which method should you use, and where do the values come from?
Show answer
Use allOf, then map the original futures with join after the combined future completes. allOf itself supplies no result list.