[英]Difference between Java8 thenCompose and thenComposeAsync
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. 我从一本书的示例中获取了这段代码,并说这两种解决方案是不同的,但是我不明白为什么。
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. 区别在于调用哪个线程generateRequest()
。
thenCompose
will call generateRequest()
on the same thread as the upstream task (or the calling thread if the upstream task has already completed). thenCompose
将在与上游任务相同的线程上调用generateRequest()
(如果上游任务已经完成,则调用线程)。
thenComposeAsync
will call generateRequest()
on the provided executor if provided, or on the default ForkJoinPool
otherwise. thenComposeAsync
将在提供的执行程序(如果提供generateRequest()
上调用generateRequest()
,否则在默认的ForkJoinPool
上调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.