关于CompletableFuture的兜底方法exceptionally的问题
CompletableFuture<String> stringFuture = CompletableFuture.supplyAsync(() -> {
String uuid = UUID.randomUUID().toString();
System.out.println("内部打印。。。uuid = " + uuid);
// int a = 1 / 0;
return uuid;
}, MyThreadPool.executorService)
.whenComplete((s, throwable) -> {
System.out.println("执行完毕后打印。。。CompleteUUID = " + s);
System.out.println(throwable.getMessage());
})
.exceptionally(throwable -> {
System.out.println(throwable.getMessage());
String uuid = UUID.randomUUID().toString();
System.out.println("exceptionally兜底打印。。。uuid = " + uuid);
return uuid;
});
String outUUID = stringFuture.get();老师,我这边不理解,为什么
stringFuture 要链式调用whenComplete、exceptionally。
为什么stringFuture 分开调用
stringFuture.whenComplete((s, throwable) -> {
System.out.println("执行完毕后打印。。。CompleteUUID = " + s);
System.out.println(throwable.getMessage());
});
stringFuture.exceptionally(throwable -> {
System.out.println(throwable.getMessage());
String uuid = UUID.randomUUID().toString();
System.out.println("exceptionally兜底打印。。。uuid = " + uuid);
return uuid;
});
String outUUID = stringFuture.get();
这样主线程为异常,无法兜底15
收起
正在回答
1回答
如果分开调用,可能会导致异常。因为异步操作完成时,whenComplete()中的处理函数执行成功,但exceptionally()中的处理函数也执行了,这可能会导致处理函数冲突或重复处理。为了避免异常,最好将whenComplete()和exceptionally()链式调用在一起,以确保异步操作的成功和异常处理逻辑清晰明确。
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星