java 的 completablefuture.thencompose 适用于“第二个异步任务依赖第一个结果”的链路:回调返回一个 future,thencompose 将它接入同一条结果链。普通同步转换使用 thenapply。以下采用 jdk 17,每节是独立 main.java,执行 javac -encoding utf-8 main.java 后用 java main 运行。

先查询用户 ID,再将结果传给异步订单任务
两次 supplyAsync 都使用显式线程池。第二个任务只有取得 userId 后才创建;thenCompose 不保证回调切换到新线程,真正的异步工作由内部 supplyAsync 提交。仅在 main 线程调用 get,避免在线程池任务内部阻塞等待同池任务。
import java.util.concurrent.*;
public class Main {
static CompletableFuture<string> loadOrders(int userId, Executor executor) {
return CompletableFuture.supplyAsync(() -> "orders-for-" + userId, executor);
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<integer> user = CompletableFuture.supplyAsync(() -> 42, pool);
CompletableFuture<string> orders = user.thenCompose(id -> loadOrders(id, pool));
String result = orders.get(3, TimeUnit.SECONDS);
if (!result.equals("orders-for-42")) throw new AssertionError();
System.out.println(result);
} finally {
pool.shutdown();
if (!pool.awaitTermination(3, TimeUnit.SECONDS)) pool.shutdownNow();
}
}
}</string></integer></string>
预期输出 orders-for-42。get 的超时限制当前等待时间,不会自动取消底层任务;生产任务仍需自己的超时和资源释放设计。这里的固定线程池在 finally 关闭,避免示例退出后继续占有线程。

区分 thenApply 的普通转换与 thenCompose 的异步接续
thenApply 回调返回普通字符串时,结果就是 CompletableFuture
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<integer> user = CompletableFuture.completedFuture(42);
CompletableFuture<string> label = user.thenApply(id -> "user-" + id);
CompletableFuture<completablefuture>> nested = user.thenApply(
id -> CompletableFuture.completedFuture("orders-for-" + id)
);
CompletableFuture<string> flat = user.thenCompose(
id -> CompletableFuture.completedFuture("orders-for-" + id)
);
if (!label.get(3, TimeUnit.SECONDS).equals("user-42")) throw new AssertionError();
if (!nested.get(3, TimeUnit.SECONDS).get(3, TimeUnit.SECONDS)
.equals(flat.get(3, TimeUnit.SECONDS))) throw new AssertionError();
System.out.println(flat.get(3, TimeUnit.SECONDS));
}
}</string></completablefuture></string></integer>
本节使用 completedFuture 只验证类型与接续关系,不创建后台线程;它不代表真实查询自动变成异步。根据回调是否返回 Future 选择方法,不应为了形式上的链式写法额外包装结果。
上游失败时,验证依赖任务不会被调用
上游异常完成后,thenCompose 的成功回调会跳过,下游结果也异常完成。用 AtomicInteger 核对回调次数,并在 get 外处理 ExecutionException,避免把失败当成普通业务返回值。
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws Exception {
AtomicInteger started = new AtomicInteger();
CompletableFuture<integer> user = CompletableFuture.failedFuture(
new IllegalArgumentException("用户不存在")
);
CompletableFuture<string> orders = user.thenCompose(id -> {
started.incrementAndGet();
return CompletableFuture.completedFuture("orders-for-" + id);
});
try {
orders.get(3, TimeUnit.SECONDS);
throw new AssertionError("应传播上游异常");
} catch (ExecutionException error) {
if (!(error.getCause() instanceof IllegalArgumentException)) throw error;
if (started.get() != 0) throw new AssertionError("不应执行依赖任务");
System.out.println(error.getCause().getMessage());
System.out.println("依赖任务次数:" + started.get());
}
}
}</string></integer>
预期打印“用户不存在”和依赖任务次数 0。这个规则只跳过依赖该失败结果的成功回调,不会撤销已经启动的无关任务;如需兜底,可在明确业务含义后再配置异常处理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










