简体   繁体   中英

Is it possible to add multiple actions to a CompletableFuture with whenComplete(…)?

The class CompletableFuture allows to add an action which is called when the future completes after calling complete(...) .

Can I use whenComplete(...) to add multiple BiConsumer actions for executing when completing the future and are all of them executed when the complete(...) method is called?

Yes, all BiConsumer actions are added and they are executed in reverse addition order when calling complete(...).

An example to demonstrate this might look like this:

public class Application {
    public static void main(String[] args) {
        System.out.println("My tests ...");
        CompletableFuture<String> futureString = new CompletableFuture<String>();
        futureString.whenComplete((s,e)->System.out.println("one " + s));
        futureString.whenComplete((s,e)->System.out.println("two " + s));
        futureString.whenComplete((s,e)->System.out.println("three " + s));
        System.out.println("do something else; "+ futureString.isDone());
        futureString.complete("step(s)");
        System.out.println("Done " + futureString.isDone());
    }
}

When running this program, the printed result looks this:

My tests ...
do something else; false 
three step(s)
two step(s)
one step(s)
Done true

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