CompletionStage whenComplete Inspects Both Paths

Observe the outcome of async work with whenComplete: the callback sees the success value or the failure exception without altering either path.

JavaResilience

Code

snippet
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class OutcomeAudit {

    // 成功与失败路径都流经同一个 whenComplete 旁路
    static CompletionStage<String> audit(CompletionStage<String> stage, String label) {
        return stage.whenComplete((value, error) -> {
            if (error != null) {
                System.out.println(label + " failed: " + error.getMessage());
            } else {
                System.out.println(label + " ok: " + value);
            }
        });
    }

    public static void main(String[] args) {
        CompletableFuture<String> ok =
                CompletableFuture.completedFuture("cache hit");
        CompletableFuture<String> boom =
                CompletableFuture.failedFuture(new IllegalStateException("pool exhausted"));

        // whenComplete 返回的新 stage 保持原结果:成功仍是成功,失败仍是失败
        audit(ok, "read").thenAccept(v -> System.out.println("downstream: " + v));
        audit(boom, "write").exceptionally(e -> "fallback")
                .thenAccept(v -> System.out.println("downstream: " + v));
    }
}

Walkthrough of the flow

Everything happens inside the class OutcomeAudit and the functions audit and main.

Points of care

  • Works with the toolchain as-is — nothing extra to add.

Putting it to use

At the boundary, the signature is static CompletionStage<String> audit(CompletionStage<String> stage, String label)

The run narrates its steps: downstream:.

The demo flow inside main is audit — run the file to see it end to end.

Core statements

CompletableFuture.failedFuture(new IllegalStateException("pool exhausted"));
CompletableFuture.completedFuture("cache hit");
return stage.whenComplete((value, error) -> {
    if (error != null) {
        System.out.println(label + " failed: " + error.getMessage());
    } else {
        System.out.println(label + " ok: " + value);
    }
});

Interactive Tools for This Topic

FAQ

What does CompletionStage whenComplete Inspects Both Paths print when run?
Execute the whole file; each printed line is prefixed with a label like `downstream:`.