![](/img/trans.png)
[英]Is the writer's reason correct for using thenCompose and not 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.