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()
,否则在默认的 ForkJoinPool
上调用。
给定这段代码:
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
上调用。