bco*_*lan 8 java concurrency java.util.concurrent
我想执行CompletableFuture一次又一次的CompletableFuture完成,无论第一个是否异常完成(.thenCompose()仅在执行正常完成时运行).
例如:
CompletableFuture.supplyAsync(() -> 1L)
.whenComplete((v, e) -> CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("HERE");
} catch(InterruptedException exc) {
return;
}
}))
.whenComplete((v, e) -> System.out.println("ALL DONE"));
Run Code Online (Sandbox Code Playgroud)
这打印
ALL DONE
HERE
Run Code Online (Sandbox Code Playgroud)
我希望它是
HERE
ALL DONE
Run Code Online (Sandbox Code Playgroud)
优选地,不将第二个嵌套在第一个whenComplete()内部.
请注意,我不关心返回的结果/异常.
诀窍是用来.handle((r, e) -> r)抑制错误:
CompletableFuture.runAsync(() -> { throw new RuntimeException(); })
//Suppress error
.handle((r, e) -> r)
.thenCompose((r) ->
CompletableFuture.runAsync(() -> System.out.println("HELLO")));
Run Code Online (Sandbox Code Playgroud)