Course contentsShow
← Java
Lesson 2861 of 2,87051. CompletableFutureFree lesson

Error Handling with anyOf

Learn how anyOf behaves when the first-completing future is exceptional versus successful.

Error Handling with anyOf

You'll learn how CompletableFuture.anyOf behaves differently depending on whether the first-completing future succeeds or fails.

The Critical Race Condition

With anyOf, whichever future completes first—whether successfully or exceptionally—determines the outcome. This creates a unique error handling scenario: an exception in the fastest future causes the entire anyOf to fail immediately, even if other futures might succeed.

Success Wins If It Arrives First

If a successful future completes before any exceptional ones, anyOf completes normally with that result:

CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(2000);
    return "Success";
});

CompletableFuture<String> fast = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(100);
    return "Quick win";
});

CompletableFuture<Object> winner = CompletableFuture.anyOf(slow, fast);
// winner completes normally with "Quick win"

Exception Wins If It Arrives First

But if an exceptional future completes first, the entire anyOf propagates that exception:

CompletableFuture<String> willFail = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(100);
    throw new RuntimeException("Fast failure");
});

CompletableFuture<String> willSucceed = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(2000);
    return "Too slow";
});

CompletableFuture<Object> result = CompletableFuture.anyOf(willFail, willSucceed);
// result completes exceptionally with RuntimeException

Recovery Pattern

Use exceptionally or handle after anyOf to provide fallback behavior:

CompletableFuture<Object> safe = CompletableFuture.anyOf(future1, future2)
    .exceptionally(ex -> "Default value if all fast futures fail");

Key Takeaway: With anyOf, the first future to complete—whether successful or exceptional—determines the entire outcome, making error handling crucial when racing unreliable tasks.