简体   繁体   中英

Completion order of CompletableFuture

I'm curious to understand the completion order when a CompletableFuture has multiple dependents. I would have expected the dependents to complete in the order they were added, but that doesn't seem to be the case.

In particular, this behaviour is surprising:

import java.util.concurrent.CompletableFuture;

public class Main {

    public static void main(String[] args) {
        {
            var x = new CompletableFuture<Void>();
            x.thenRun(() -> System.out.println(1));
            x.thenRun(() -> System.out.println(2));
            x.thenRun(() -> System.out.println(3));
            x.complete(null);
        }
        {
            var x = new CompletableFuture<Void>();
            var y = x.copy();
            y.thenRun(() -> System.out.println(1));
            y.thenRun(() -> System.out.println(2));
            y.thenRun(() -> System.out.println(3));
            x.complete(null);
        }
    }
}

...results in the the following output...

3
2
1
1
2
3

All 3 child futures generated by 'x.thenRun()' expression run in parallel, so you cannot expect any particular order of printed numbers.

The same for 'y.thenRun()'.

The expressed order is an implementation feature, can change in the future, and is not supported by the specification.

So you have not chained those thenRun , as such there are zero guarantees on the order, but you expect some order? Sorry, that's not how it works.

The documentation does not say anything about order of execution in such cases, so whatever you see now in the output:

  • is not a guarantee
  • can change from run to run (and from java version to version)

It is a little bit hard to prove via code with your current set-up, but just change it to:

var x = CompletableFuture.runAsync(() -> {
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        });
x.thenRun(() -> System.out.println(1));
x.thenRun(() -> System.out.println(2));
x.thenRun(() -> System.out.println(3));
x.join();

And run this let's say 20 times , I bet that at least once, you will not see 3, 2, 1 , but something different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM