gpt4 book ai didi

java - Java8 thenCompose 和 thenComposeAsync 之间的区别

转载 作者:行者123 更新时间:2023-12-02 07:44:43 30 4
gpt4 key购买 nike

鉴于这段代码:

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()(如果提供),否则在默认的 ForkJoinPool 上调用。

关于java - Java8 thenCompose 和 thenComposeAsync 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130969/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com