Suppose I have the following code:
CompletableFuture future
= CompletableFuture.supplyAsync( () -> 0);
thenAp
The second step (i.e. computation) will always be executed after the first step.
If the second step has to wait for the result of the first step then what is the point of Async?
Async means in this case that you are guaranteed that the method will return quickly and the computation will be executed in a different thread.
When calling thenApply
(without async), then you have no such guarantee. In this case the computation may be executed synchronously i.e. in the same thread that calls thenApply
if the CompletableFuture is already completed by the time the method is called. But the computation may also be executed asynchronously by the thread that completes the future or some other thread that calls a method on the same CompletableFuture
. This answer: https://stackoverflow.com/a/46062939/1235217 explained in detail what thenApply does and does not guarantee.
So when should you use thenApply
and when thenApplyAsync
? I use the following rule of thumb: