Re: Counter-intuitive behavior of CompleteableFuture
Benjamin Manes via Concurrency-interest <[email protected]> Thu, 20 May 2021 05:40:11 -0700
| Newsgroups | gmane.comp.java.jsr.166-concurrency |
|---|---|
| Message-ID | <CAGu0=MPAb88oYrAYetx-+HWeTSYRMcpYpGPZ=Ldn3PHsutZrQg@mail.gmail.com> |
The timeout is applied to the STEP2 future which completes it exceptionally. This causes it to not run the mapping function for a result, as it was completed prior to that being triggered. You can use copy() to decouple the source from the timeout if you want both to complete; e.g. cache a long running value but fail a consumer if taking to long. On Thu, May 20, 2021 at 5:31 AM Michał Górniewski via Concurrency-interest < [email protected]> wrote: > With following code: > > ------------------------------ > public static void main(String[] args) { > CompletableFuture<String> initial = new CompletableFuture<>(); > > CompletableFuture<String> withSteps = initial > .thenApply(s -> { > System.out.println("STEP1: " + s); > return s; > }) > .thenApply(s -> { > System.out.println("STEP2: " + s); > return s; > }); > > CompletableFuture<String> timeout = withSteps; > > timeout.whenComplete((s, throwable) -> > System.out.println("TIMEOUT: " + throwable)); > > timeout.completeExceptionally(new RuntimeException("TIMEOUT")); > initial.complete("SUCCESS"); > } > ------------------------------ > > I got output like this: > > ------------------------------ > TIMEOUT: java.lang.RuntimeException: TIMEOUT > STEP1: SUCCESS > ------------------------------ > > I don't understand why "STEP2" is not executed in this case. Is this > expected? > For me this API is confusing and may create issues like this: > https://github.com/resilience4j/resilience4j/issues/1427 > > Thanks, > Michał Górniewski > _______________________________________________ > Concurrency-interest mailing list > [email protected] > http://cs.oswego.edu/mailman/listinfo/concurrency-interest > _______________________________________________ Concurrency-interest mailing list [email protected] http://cs.oswego.edu/mailman/listinfo/concurrency-interest