Sub topic 7
Running many tasks with allOf and anyOf
This chapter assumes you know supplyAsync, thenApply, join, and how a failed stage reports its exception wrapped in a CompletionException. Earlier chapters covered all of these.
thenCombine merges exactly two futures. Real programs often start a dozen calls, such as one per page, shard, or mirror server. They then need either all the results or the first one. CompletableFuture.allOf and CompletableFuture.anyOf handle those two cases.
The shape of the two methods
Both methods are static and take a varargs array of futures. Their return types differ in a way that shapes how you use them.
| Method | Returns | Completes when | Value |
|---|---|---|---|
| `allOf(cfs...)` | `CompletableFuture<Void>` | every input has completed | always `null` |
| `anyOf(cfs...)` | `CompletableFuture<Object>` | the first input completes | that input's result, or its exception |
The inputs may have different result types, so Java cannot give a precise result type for either method. allOf returns no values at all. anyOf returns a plain Object that you must cast.
Waiting for everything with allOf
The returned future is a signal, not a container. Once it completes, you read each input future yourself. Calling join at that point is safe because every input is already complete, so join returns immediately and blocks nothing.
The following helper turns a list of futures into one future of a list. It keeps the order of the input list, not the order of completion.
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class Gather {
static <T> CompletableFuture<List<T>> allAsList(List<CompletableFuture<T>> futures) {
return CompletableFuture
.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
public static void main(String[] args) {
List<CompletableFuture<String>> pages = List.of("a", "b", "c").stream()
.map(s -> CompletableFuture.supplyAsync(() -> s.toUpperCase()))
.collect(Collectors.toList());
System.out.println(allAsList(pages).join());
}
}This prints [A, B, C]. The toArray(new CompletableFuture[0]) call is needed because Java cannot create arrays of a parameterized type such as CompletableFuture<String>[]. The raw array is accepted by allOf, whose parameter type is CompletableFuture<?>....
Two points about this helper:
- The
joincalls insidethenApplynever block. They run only afterallOfhas completed, so each input is already done. - If you called
joinon each future beforeallOfcompleted, you would block a thread, which defeats the point of composing futures.
Edge case: an empty array
allOf() with no arguments returns a future that is already complete with null. With an empty list, the helper above therefore produces an empty list immediately. anyOf() with no arguments behaves differently, as described below.
What happens when one task fails
allOf does not fail fast. If one input fails, the returned future still waits for all the others to finish. It then completes exceptionally with a CompletionException whose cause is the failure of one of the failed inputs. If several inputs fail, you cannot rely on which exception is reported.
The following program shows the delay.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class AllOfFailure {
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
CompletableFuture<String> fast = CompletableFuture.supplyAsync(() -> {
throw new IllegalStateException("boom");
});
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
sleep(500);
return "slow";
});
long start = System.nanoTime();
try {
CompletableFuture.allOf(fast, slow).join();
} catch (CompletionException e) {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("waited at least 400 ms: " + (ms >= 400));
System.out.println("cause: " + e.getCause());
}
}
}The output is:
waited at least 400 ms: true
cause: java.lang.IllegalStateException: boomThe first task failed almost at once, but the caller learned about it only after the slow task finished.
Fail-fast variant
If you want to report the first failure immediately, build your own result future and complete it from each input.
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class FailFast {
static <T> CompletableFuture<List<T>> allFailFast(List<CompletableFuture<T>> futures) {
CompletableFuture<List<T>> result = new CompletableFuture<>();
for (CompletableFuture<T> f : futures) {
f.whenComplete((v, ex) -> {
if (ex != null) {
result.completeExceptionally(ex);
}
});
}
Gather.allAsList(futures).thenAccept(result::complete);
return result;
}
}This class reuses allAsList from the earlier example, so keep both classes in the same package. The first failing input completes result exceptionally. A later call to complete or completeExceptionally has no effect, because a future completes only once. The remaining tasks keep running, because nothing here cancels them.
Tolerating partial failure
Sometimes you want every result that succeeded. Attach a handle to each input before passing it to allOf, and turn failures into a placeholder value:
CompletableFuture<String> safe = original.handle((v, ex) -> ex == null ? v : "n/a");Every future in the group then completes normally, so allOf never fails. Choose a placeholder you can tell apart from real data. An Optional<T> works well.
Taking the first result with anyOf
anyOf completes as soon as any input completes, in either state. If the first input to finish failed, the anyOf future fails too, even when other inputs would have succeeded a moment later. A fast failure beats a slow success.
The result type is Object. The following version restores a type with a helper method.
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class AnyOfDemo {
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static CompletableFuture<String> mirror(String name, long delayMs) {
return CompletableFuture.supplyAsync(() -> {
sleep(delayMs);
return name;
});
}
@SuppressWarnings("unchecked")
static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures) {
return CompletableFuture
.anyOf(futures.toArray(new CompletableFuture[0]))
.thenApply(o -> (T) o);
}
public static void main(String[] args) {
String winner = firstOf(List.of(
mirror("eu", 300),
mirror("us", 100),
mirror("asia", 500))).join();
System.out.println(winner);
}
}The program prints us. The cast is unchecked, but it is safe here because the generic signature guarantees every input produces a T.
What anyOf does not do
- It does not cancel the losers. The
euandasiatasks above keep running until they finish, and their results are ignored. If the tasks are expensive, keep the list of futures and callcancel(true)on the others. Remember that cancelling aCompletableFuturedoes not interrupt the thread running the task. It only completes the future with aCancellationException. - It does not ignore failures. If you want the first success, wrap each input with
handleorexceptionallyso that failures never complete the group first. Then you must decide what happens when every input fails. anyOf()with an empty array returns a future that never completes. Joining it blocks forever, so check for an empty list before calling it.
Choosing an executor for many tasks
All the examples above use the common pool, which is fine for short CPU-bound work. For many blocking calls, such as HTTP requests or database queries, pass a dedicated executor to each supplyAsync. The common pool has roughly one thread per core, so a hundred blocking tasks would run a few at a time and starve unrelated code. A fixed pool sized for the downstream service gives you control over concurrency. Shut the pool down when the work is finished.
Summary of rules
- Use
allOfwhen you need every result. Read the values withjoininside a stage that runs after it. - Remember that
allOfwaits for the slowest input even after a failure. Build a fail-fast wrapper when that delay is unacceptable. - Use
anyOffor the first result, and cast or wrap it to restore a type. - Guard against empty inputs.
allOf()completes at once, andanyOf()never does. - Cancel or ignore the losers deliberately, since nothing does it for you.
Exercise
A list of five futures calls five services. One service fails after 50 ms, and the slowest of the others takes 2 seconds. You call allOf(...) on the list and attach exceptionally to the result. Roughly when does the exceptionally handler run, and what does it receive?
Show answer
It runs after about 2 seconds, when the slowest future finishes, because allOf waits for all inputs even after one fails. The handler receives a CompletionException whose cause is the exception thrown by the failed service. To react after 50 ms, build a fail-fast wrapper that calls completeExceptionally on a result future from a whenComplete attached to each input.
Exercise
You use anyOf over three mirror downloads. The fastest mirror throws an exception after 20 ms, and the other two would succeed after 200 ms. What does join on the anyOf future do, and how would you change the code to get the first successful download instead?
Show answer
join throws a CompletionException after about 20 ms, because the first input to complete, even exceptionally, completes the anyOf future. To get the first success, wrap each download with handle or exceptionally so failures do not complete the group early, for example by mapping them to null or an Optional.empty(). Then complete a result future manually from the first non-empty value, and fail it only if every input failed.