What is the difference between thenApply and thenApplyAsync of Java CompletableFuture?

后端 未结 4 1913
渐次进展
渐次进展 2021-01-31 02:24

Suppose I have the following code:

CompletableFuture future  
        = CompletableFuture.supplyAsync( () -> 0);

thenAp

4条回答
  •  伪装坚强ぢ
    2021-01-31 02:31

    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:

    • non-async: only if the task is very small and non-blocking, because in this case we don't care which of the possible threads executes it
    • async (often with an explicit executor as parameter): for all other tasks

提交回复
热议问题