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

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

Suppose I have the following code:

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

thenAp

4条回答
  •  旧巷少年郎
    2021-01-31 02:31

    The difference has to do with the Executor that is responsible for running the code. Each operator on CompletableFuture generally has 3 versions.

    1. thenApply(fn) - runs fn on a thread defined by the CompleteableFuture on which it is called, so you generally cannot know where this will be executed. It might immediately execute if the result is already available.
    2. thenApplyAsync(fn) - runs fn on a environment-defined executor regardless of circumstances. For CompletableFuture this will generally be ForkJoinPool.commonPool().
    3. thenApplyAsync(fn,exec) - runs fn on exec.

    In the end the result is the same, but the scheduling behavior depends on the choice of method.

提交回复
热议问题