Counter-intuitive behavior of CompleteableFuture

Pavel Rappo pavel.rappo at oracle.com
Thu May 20 10:26:28 UTC 2021


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