Difference between Java8 thenCompose and thenComposeAsync

你说的曾经没有我的故事 提交于 2019-12-23 03:18:09

问题


Given this piece of code:

public List<String> findPrices(String product){
    List<CompletableFuture<String>> priceFutures =
    shops.stream()
         .map(shop -> CompletableFuture.supplyAsync(
                () -> shop.getPrice(product), executor))
         .map(future -> future.thenApply(Quote::parse))
         .map(future -> future.thenCompose(quote ->
                CompletableFuture.supplyAsync(
                        () -> Discount.applyDiscount(quote), executor
                )))
         .collect(toList());

    return priceFutures.stream()
                       .map(CompletableFuture::join)
                       .collect(toList());
}

This part of it:

.map(future -> future.thenCompose(quote ->
                CompletableFuture.supplyAsync(
                        () -> Discount.applyDiscount(quote), executor
                )))

Could it be rewrite as:

.map(future -> 
    future.thenComposeAsync(quote -> Discount.applyDiscount(quote), executor))

I took this code from an example of a book and says the two solutions are different, but I do not understand why.


回答1:


Let's consider a function that looks like this:

public CompletableFuture<String> requestData(String parameters) {
    Request request = generateRequest(parameters);
    return CompletableFuture.supplyAsync(() -> sendRequest(request));
}

The difference will be with respect to which thread generateRequest() gets called on.

thenCompose will call generateRequest() on the same thread as the upstream task (or the calling thread if the upstream task has already completed).

thenComposeAsync will call generateRequest() on the provided executor if provided, or on the default ForkJoinPool otherwise.



来源:https://stackoverflow.com/questions/46130969/difference-between-java8-thencompose-and-thencomposeasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!