在 java 中实现 completablefuture 的串行执行,核心方法是使用 thenapply、thenaccept 或 thenrun 等链式调用方法。这些方法会确保前一个任务完成后,再按顺序执行后续任务,从而形成一条线性的执行流。

如何传递上一个任务的计算结果给下一个任务
要实现数据在串行步骤间的传递,必须使用带有 Consumer 或 Function 参数的方法,如 thenApply 或 thenCompose。这些方法会将前一步的返回值作为参数传递给下一步,从而实现数据的流转。

import java.util.concurrent.CompletableFuture;
public class SerialExample {
public static void main(String[] args) throws Exception {
// 定义初始值
Integer initialData = 10;
// 构建串行执行链
CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> {
System.out.println("Step 1: Initial value is " + initialData);
return initialData;
})
.thenApply(data -> {
System.out.println("Step 2: Doubling the value to " + (data * 2));
return data * 2;
})
.thenApply(data -> {
System.out.println("Step 3: Adding 5 to get " + (data + 5));
return data + 5;
});
// 获取最终结果
Integer result = future.get();
System.out.println("Final Result: " + result);
}
}
如何处理串行执行中的异常
当串行链中的某个步骤抛出异常时,后续的 thenApply 步骤将不会执行。为了保持流程继续或捕获错误,可以使用 exceptionally 或 handle 方法。exceptionally 允许你提供一个默认值或替代逻辑来恢复执行。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
public class ErrorHandlingExample {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> {
throw new RuntimeException("Simulated error in step 1");
})
.thenApply(s -> s.toUpperCase()) // This will not execute
.exceptionally(throwable -> {
System.out.println("Caught exception: " + throwable.getMessage());
return "Default Value"; // Return a fallback value
});
String result = future.get();
System.out.println("Result after error handling: " + result);
}
}
基于输入为 null 时的具体行为问题
如果串行链中的某个步骤返回了 null,后续依赖该结果的步骤(如 thenApply)将会接收到 null 作为输入。这可能导致 NullPointerException,除非你在后续步骤中显式处理了空值情况。

















