在 java 8 引入的 completablefuture 中,thenapply 方法用于在当前异步任务完成时,获取其结果并立即进行同步转换,返回一个新的包含转换后结果的 completablefuture。它适用于非阻塞的计算场景,通过链式调用将多个处理步骤串联起来,避免手动管理线程和回调逻辑。

thenApply 与 thenAccept 的区别是什么
thenApply 必须返回一个值,而 thenAccept 接收值但不返回任何内容(void)。这意味着 thenApply 可以进一步链接其他操作,而 thenAccept 通常作为链的终点或用于副作用操作如日志记录。

import java.util.concurrent.CompletableFuture;
public class Demo {
public static void main(String[] args) throws Exception {
// 使用 thenAccept 打印结果,无返回值
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(result -> System.out.println("Received: " + result));
// 等待完成
future.join();
}
}</string>
thenApply 如何处理异常
thenApply 本身不处理异常,如果上游任务抛出异常,下游的 thenApply 不会执行。需要使用 exceptionally 或 handle 方法来捕获和处理异常,确保流程继续或提供默认值。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

import java.util.concurrent.CompletableFuture;
public class ErrorDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error occurred");
}).exceptionally(ex -> "Default Value");
String result = future.join();
System.out.println(result); // 输出: Default Value
}
}</string>
thenApply 在链式调用中的具体表现
当多个 thenApply 串联时,每个步骤的结果都会传递给下一个步骤。如果中间步骤抛出未捕获的异常,整个链会中断,后续步骤不会执行。可以通过在每个步骤后添加 exception 处理来增强鲁棒性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










