I came across the strange behavior of the Java 8 method CompletableFuture thenCompose. I have two tests that differ only in the order of execution. Both tests simulate a failure in the CompletableFuture generated in thenCompose.
@Test public void completedAfter() { CompletableFuture<String> future1 = new CompletableFuture<>(); CompletableFuture<String> future2 = new CompletableFuture<>(); future1.thenCompose(x -> future2).whenComplete((r, e) -> System.out.println("After: " + e)); future1.complete("value"); future2.completeExceptionally(new RuntimeException()); } @Test public void completedBefore() { CompletableFuture<String> future1 = new CompletableFuture<>(); CompletableFuture<String> future2 = new CompletableFuture<>(); future1.complete("value"); future2.completeExceptionally(new RuntimeException()); future1.thenCompose(x -> future2).whenComplete((r, e) -> System.out.println("Before: " +e)); }
Output:
After: java.util.concurrent.CompletionException: java.lang.RuntimeException Before: java.lang.RuntimeException
The question is why the exception is thrown in a CompletionException in one case, but not in another?
Update: An error report is linked here . It has been flagged and resolved as a bug in the JDK.
java java-8 future
Lukas
source share