Java 并发学习专题

CompletableFuture:异常、超时与取消的边界

复现异常兜底、orTimeout、allOf 异常和 cancel(true) 后任务仍可继续的行为,区分 Future 完成状态与底层业务执行。

简明结论

Future 超时或取消不等于底层 I/O 已停止。异常兜底应保留错误语义,超时还需要下游截止时间与业务清理配合。

给 CompletableFuture 加 orTimeout,是否就不会继续占用下游资源?不能这样推断。Future 的完成状态与实际执行的操作需要分别管理。

可复现程序

保存为 FutureOutcomes.java,执行 java FutureOutcomes.java。本例需要 JDK 21;orTimeout 自 Java 9 起提供,不适用于原样运行在 Java 8 的代码。

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class FutureOutcomes {
  public static void main(String[] args) throws Exception {
    CompletableFuture<String> failed = CompletableFuture.failedFuture(new IllegalStateException("demo"));
    System.out.println("fallback=" + failed.exceptionally(error -> "cached").join());
    CompletableFuture<String> pending = new CompletableFuture<>();
    System.out.println("timeout=" + pending.orTimeout(20, TimeUnit.MILLISECONDS)
        .handle((value, error) -> error == null ? value : error.getClass().getSimpleName()).join());
    ExecutorService pool = Executors.newSingleThreadExecutor();
    CountDownLatch started = new CountDownLatch(1), release = new CountDownLatch(1), finished = new CountDownLatch(1);
    AtomicBoolean interrupted = new AtomicBoolean();
    try {
      CompletableFuture<String> work = CompletableFuture.supplyAsync(() -> {
        started.countDown();
        try { release.await(); return "done"; }
        catch (InterruptedException error) { interrupted.set(true); Thread.currentThread().interrupt(); return "interrupted"; }
        finally { finished.countDown(); }
      }, pool);
      if (!started.await(5, TimeUnit.SECONDS)) throw new AssertionError("not started");
      boolean cancelled = work.cancel(true);
      release.countDown();
      if (!finished.await(5, TimeUnit.SECONDS)) throw new AssertionError("not finished");
      System.out.println("cancelled=" + cancelled + "; worker-finished=true; interrupted=" + interrupted.get());
      CompletableFuture<Void> all = CompletableFuture.allOf(failed, CompletableFuture.completedFuture("ok"));
      System.out.println("allOf-failed=" + all.handle((value, error) -> error != null).join());
    } finally { release.countDown(); pool.shutdownNow(); }
  }
}

预期输出:

fallback=cached
timeout=TimeoutException
cancelled=true; worker-finished=true; interrupted=false
allOf-failed=true

超时示例使用一个不会主动完成的 Future,20 毫秒是触发超时所设的演示值,不是实际耗时承诺。取消示例先确认任务已经启动,再取消 Future、放行任务;任务仍走到结束,且没有因为 cancel(true) 收到中断。

各种处理方式保留什么语义

exceptionally 可以生成替代值,但替代值应能区分“查询成功但为空”和“依赖失败后兜底”。handle 观察成功或失败并产生新结果;whenComplete 适合观察完成状态,回调自身抛错也会影响后续结果。

allOf 返回 CompletableFuture<Void>,表示整体完成,不自动返回结果列表;只有聚合成功后,才应按业务收集各个结果。本例只检查其中一个阶段失败导致聚合失败,没有验证多依赖同时失败时的错误归因。

应用到远程调用时

把请求总预算传给下游,分别设置连接、读取等超时,并确认客户端取消是否真正关闭请求。重试需要幂等性、次数与退避限制。本文没有接入网络客户端,也没有证明“取消可节省多少资源”。

原资料原作者与原始链接待确认;这里的取消演示、输出和边界说明为本站新增。API 语义按 JDK 21 核对。

继续阅读结果组合和线程池拒绝策略。