Need to confirm something. The following code:
CompletableFuture
.supplyAsync(() -> {return doSomethingAndReturnA();})
.thenApply(a -> convertToB(a));
would be the same as:
CompletableFuture
.supplyAsync(() -> {
A a = doSomethingAndReturnA();
convertToB(a);
});
Right?
Furthermore, another two questions following as for "is there any reason why we would use thenApply
?"
1) having big code for conversion?
or
2) need to reuse the lambda block in other places?
Best Answer
It is not the same thing. In the second example where
thenApply
is not used it is certain that the call toconvertToB
is executed in the same thread as the methoddoSomethingAndReturnA
.But, in the first example when the
thenApply
method is used other things can happen.First of all, if the
CompletableFuture
that executes thedoSomethingAndReturnA
has completed, the invocation of thethenApply
will happen in the caller thread. If theCompletableFutures
hasn't been completed theFunction
passed tothenApply
will be invoked in the same thread asdoSomethingAndReturnA
.Confusing? Well this article might be helpful (thanks @SotiriosDelimanolis for the link).
I have provided a short example that illustrates how
thenApply
works.And the output is:
So, when the first operation is slow (i.e. the
CompletableFuture
is not yet completed) both calls occur in the same thread. But if the we were to remove theThread.sleep
-call from thedoSomethingAndReturnA
the output (may) be like this:Note that
convertToB
call is in themain
thread.