CompletableFuture AnyOf When Fastest Fails
CompletableFuture.anyOf settles on the first completed stage even if it failed, so wrap noisy mirrors with exceptionally before racing them.
Code
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ResilientRace {
static CompletableFuture<String> replica(String name, long delayMs, boolean fail) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (fail) {
throw new IllegalStateException(name + " failed");
}
return name + "-ok";
});
}
public static void main(String[] args) {
// Raw anyOf resolves with the fastest completion, even when it throws
CompletableFuture<Object> raw = CompletableFuture.anyOf(
replica("fast-broken", 15, true),
replica("slow-healthy", 80, false));
try {
System.out.println("raw winner: " + raw.join());
} catch (CompletionException ex) {
String msg = ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage();
System.out.println("raw anyOf failed fast: " + msg);
}
// Guard each branch so a failed fast mirror degrades cleanly
CompletableFuture<String> safeA = replica("fast-broken", 15, true)
.exceptionally(err -> "fallback-" + (err.getCause() != null ? err.getCause().getMessage() : err.getMessage()));
CompletableFuture<String> safeB = replica("slow-healthy", 80, false);
CompletableFuture<Object> safe = CompletableFuture.anyOf(safeA, safeB);
System.out.println("guarded winner: " + safe.join());
safeB.join();
}
}Runtime walkthrough — CompletableFuture AnyOf When Fastest Fails
The snippet is organized around the class ResilientRace and the functions replica and main.
Invalid states are rejected up front: it throws IllegalStateException instead of continuing with bad data.
What to watch for
- Any import statements listed strictly target bundled standard modules.
Applying it
Entry signature: static CompletableFuture<String> replica(String name, long delayMs, boolean fail)
The run emits 3 labeled sections — raw winner:, raw anyOf failed fast:, guarded winner: — one per step.
There are 1 call inside main — replica — executed top to bottom.
Statements that matter
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (fail) {
throw new IllegalStateException(name + " failed");
}
return name + "-ok";
});
CompletableFuture<Object> safe = CompletableFuture.anyOf(safeA, safeB);
CompletableFuture<String> safeB = replica("slow-healthy", 80, false);
Interactive Tools for This Topic
FAQ
- What does the snippet do with malformed data?
- `IllegalStateException` is raised at the guard, so invalid state never reaches the main logic.
- What does CompletableFuture AnyOf When Fastest Fails print when run?
- No setup needed: run the file and look for labeled lines like `raw winner:`, `raw anyOf failed fast:`, `guarded winner:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.