Counter-intuitive behavior of CompleteableFuture
Michał Górniewski
michal.gorniewski at gmail.com
Thu May 20 12:25:13 UTC 2021
For me this is a somewhat confusing API. I've stumble upon this while
using resilience4j library:
https://github.com/resilience4j/resilience4j/issues/1427
I will open a thread on concurrency-interest.
Thanks,
Michał
czw., 20 maj 2021 o 12:26 Pavel Rappo <pavel.rappo at oracle.com> napisał(a):
>
> 1. Haven't you effectively cancelled "STEP 2" by completing the respective future exceptionally?
> 2. If you need a result of a future at some point, wait for it:
>
> timeout.join() (or use an overload of CompletableFuture.get)
>
> Questions related to the contents of java.util.concurrent.** should generally be asked on the "Concurrency-interest" mailing list: http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>
> > On 20 May 2021, at 10:07, Michał Górniewski <michal.gorniewski at gmail.com> wrote:
> >
> > Hi,
> >
> > 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?
> >
> > Thanks,
> > Michał Górniewski
>
More information about the discuss
mailing list