Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement