Counter-intuitive behavior of CompleteableFuture

Michał Górniewski michal.gorniewski at gmail.com
Thu May 20 09:07:30 UTC 2021


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