exceptionallyCompose Chains A Fallback Future

exceptionallyCompose swaps a failed future for a fallback future instead of a plain value, so recovery can itself be an async call.

JavaResilience

Code

snippet
import java.util.concurrent.CompletableFuture;

public class FallbackChain {

    public static void main(String[] args) throws Exception {
        CompletableFuture<String> primary = new CompletableFuture<>();
        primary.completeExceptionally(new IllegalStateException("primary source down"));

        // exceptionallyCompose 接住异常并 chains a fallback future,恢复本身可以是异步调用
        CompletableFuture<String> recovered = primary
                .exceptionallyCompose(cause -> {
                    System.out.println("cause: " + cause.getMessage());
                    return CompletableFuture.completedFuture("from replica");
                });

        System.out.println("recovered: " + recovered.get());

        // 成功路径完全不触发替补
        CompletableFuture<String> healthy = CompletableFuture.completedFuture("from primary");
        System.out.println("healthy: "
                + healthy.exceptionallyCompose(ignored -> CompletableFuture.completedFuture("unused")).get());
    }
}

How the code works

All of the logic lives in the class FallbackChain.

What to watch for

  • Free of dependencies by construction — a registry and a lockfile never come into play.

Using it

The output announces the file’s steps: cause:, recovered:, healthy:.

Key statements

return CompletableFuture.completedFuture("from replica");
CompletableFuture<String> healthy = CompletableFuture.completedFuture("from primary");
CompletableFuture<String> primary = new CompletableFuture<>();

Interactive Tools for This Topic

FAQ

What does exceptionallyCompose Chains A Fallback Future print when run?
Execute the whole file; each printed line is prefixed with a label like `cause:`, `recovered:`, `healthy:`.