给出这段代码:
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
上调用ojit_code。关于java - Java8 thenCompose和thenComposeAsync之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46130969/