← 中文资源

简体中文版本

whenComplete 观测完成的双路径

用 whenComplete 挂同一个回调观察成功值或失败异常:结果不改动、异常继续向后传播,下游可用 exceptionally 兜底。

阅读英文原文

实现说明

活动部件是类 OutcomeAudit和函数 audit、main。

使用要点

  • 直接运行文件,输出会带上标签,比如 downstream:——输出的每一行都能指回产生它的那次调用。
  • main 的演示流程是 audit——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「whenComplete 观测完成的双路径」会打印什么?

整个文件跑完,输出行以 downstream: 这类前缀开头。

主签名形如 static CompletionStage<String> audit(CompletionStage<String> stage, String label)

核心语句

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);
    }
});

代码示例

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));
    }
}