簡體   English   中英

Java8 thenCompose和thenComposeAsync之間的區別

[英]Difference between Java8 thenCompose and thenComposeAsync

給出這段代碼:

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());
}

這部分內容:

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

可以改寫為:

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

我從一本書的示例中獲取了這段代碼,並說這兩種解決方案是不同的,但是我不明白為什么。

讓我們考慮一個看起來像這樣的函數:

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

區別在於調用哪個線程generateRequest()

thenCompose將在與上游任務相同的線程上調用generateRequest() (如果上游任務已經完成,則調用線程)。

thenComposeAsync將在提供的執行程序(如果提供generateRequest()上調用generateRequest() ,否則在默認的ForkJoinPool上調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM