gal11111
gal11111

Reputation: 21

CompletableFuture in case of if statment

I have 2 CompletableFutures and 3 methods that have to occur each after the other. However, in some cases the second method isn't necessary.

        CompletableFuture<Boolean> cf1 = supplyASync.(() ->( doSomething1()));

        CompletableFuture<Boolean> cf2 = new CompletableFuture<Boolean>();
        if(someThing){
            cf2 = cf1.thenApplyAsync(previousResult -> doSomething2()); 
        }
        else{
            cf2 = cf1;
        }

        if (SomeThing2) {       
            cf2.thenApplyAsync(previousResult ->doSomeThing3());

        }

Bassicly what I'm trying to do is that doSomething2 will run after doSomething1 (if needed), but anyway that doSomeThing3 will execute after the first or both of them.

  1. Is it the right way to do it ? Or is there better way ?

Upvotes: 2

Views: 1039

Answers (1)

Jose da Silva Gomes
Jose da Silva Gomes

Reputation: 3974

The code is being executed in sequence, that is first completable future 1, then completable future 2 (if applies) and finally task 3.

By this reason, you can use a single CompletableFuture:

CompletableFuture<Boolean> cf = CompletableFuture.supplyAsync(() -> {
    if (doSomething1()) {
        doSomething2();
    }
    doSomething3();
    // return something
});

And handling the boolean results would be something like:

CompletableFuture<Boolean> cf = CompletableFuture.supplyAsync(() -> {
    boolean result;
    if (result = doSomething1()) {
        result = doSomething2();
    }
    return result && doSomething3();
});
// handle future as you need, e.g. cf.get() to wait the future to end (after task 3)

Upvotes: 1

Related Questions