在 java 中,使用 completablefuture 的 whencomplete 方法可以在异步任务完成时(无论成功还是异常)执行回调逻辑。调用该方法会返回一个新的 completablefuture,其结果与原任务一致,且回调函数接收原任务的返回值和可能抛出的异常。通过这种方式,你可以在不中断主流程的情况下统一处理日志记录、资源清理或异常捕获。

whenComplete 与 exceptionally 的区别是什么
whenComplete 能够同时获取正常结果和异常信息,而 exceptionally 仅在发生异常时触发并允许提供替代值。如果需要在成功和失败两种场景下都执行相同的清理代码,应优先选择 whenComplete;若只需针对错误进行恢复,则使用 exceptionally。两者均不会改变上游传递的结果,除非在回调中显式抛出新的异常。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class WhenCompleteDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟业务逻辑
return "Success";
});
// 使用 whenComplete 处理回调
CompletableFuture<String> resultFuture = future.whenComplete((result, throwable) -> {
if (throwable != null) {
System.out.println("Error occurred: " + throwable.getMessage());
} else {
System.out.println("Result is: " + result);
}
});
// 获取最终结果
String finalResult = resultFuture.get();
System.out.println("Final Result: " + finalResult);
}
}
运行上述代码将输出:
Result is: Success
Final Result: Success
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
如何在 whenComplete 中修改返回结果
whenComplete 的回调方法签名是 void accept(T t, Throwable throwable),它没有返回值,因此无法直接修改上游传递的结果。如果需要基于原结果计算新值,必须使用 thenApply 或 handle 方法。但在某些情况下,你可能希望在回调中根据条件决定后续行为,此时可以通过抛出异常来中断流程,或者结合 completeExceptionally 手动设置异常状态。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class HandleModificationDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10);
// 使用 handle 修改结果
CompletableFuture<Integer> modifiedFuture = future.handle((result, throwable) -> {
if (throwable != null) {
return -1; // 默认值
}
return result * 2; // 修改结果
});
Integer newValue = modifiedFuture.get();
System.out.println("Modified Value: " + newValue);
}
}
运行上述代码将输出:Modified Value: 20
当异步任务抛出未捕获异常时 whenComplete 的行为如何
当异步任务内部抛出未捕获异常时,whenComplete 的第二个参数 throwable 将包含该异常对象,而第一个参数 t 为 null。此时,由 whenComplete 返回的新 CompletableFuture 将处于异常完成状态。如果未在后续链中处理该异常,它将传播至调用 get() 或阻塞等待的地方。这种机制确保了即使出现错误,也能通过统一的回调入口进行监控和记录,避免静默失败。

















