简体   繁体   中英

CompletableFuture exception chaining

I want to wait for multiple events and decided to try to implement that with CompletableFuture.

CompletableFuture a1 = new CompletableFuture();
CompletableFuture a2 = new CompletableFuture();
CompletableFuture a3 = new CompletableFuture();
CompletableFuture b = new CompletableFuture();
CompletableFuture subFuturesA= CompletableFuture.allOf(a1, a2, a3);
CompletableFuture andB = CompletableFuture.allOf(b, subFuturesA);
andB.handle((result, exception) -> { System.out.println("Test"); return result; });

If I complete all futures with:

a1.complete(null);
a2.complete(null);
a3.complete(null);
b.complete(null);

the string Test is printed. But if I have an error in one event and use a1.completeExceptionally(new IllegalStateException()); the string is not printed. It still waits for the others to complete. How can I combine completableFutures so that one completeExceptionally triggers the handle method?

According to the docs The CompleteableFuture created from the allOf method will complete when

all of the given CompletableFutures complete.

They all must complete for the combined one to complete otherwise it wouldn't be doing it's job regardless of one completely exceptionally.

You can create an an 'exceptionally' CompleteableFuture for each one then combine those with an anyOf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM