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

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

Suppose I have the following code:

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

thenAp

4条回答
  •  爱一瞬间的悲伤
    2021-01-31 02:36

    This is what the documentation says about CompletableFuture's thenApplyAsync:

    Returns a new CompletionStage that, when this stage completes normally, is executed using this stage's default asynchronous execution facility, with this stage's result as the argument to the supplied function.

    So, thenApplyAsync has to wait for the previous thenApplyAsync's result:

    In your case you first do the synchronous work and then the asynchronous one. So, it does not matter that the second one is asynchronous because it is started only after the synchrounous work has finished.

    Let's switch it up. In some cases "async result: 2" will be printed first and in some cases "sync result: 2" will be printed first. Here it makes a difference because both call 1 and 2 can run asynchronously, call 1 on a separate thread and call 2 on some other thread, which might be the main thread.

    CompletableFuture future
                    = CompletableFuture.supplyAsync(() -> 0);
    
    future.thenApplyAsync(x -> x + 1) // call 1
                    .thenApplyAsync(x -> x + 1)
                    .thenAccept(x -> System.out.println("async result: " + x));
    
    future.thenApply(x -> x + 1) // call 2
                    .thenApply(x -> x + 1)
                    .thenAccept(x -> System.out.println("sync result:" + x));
    

提交回复
热议问题