13

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.

Cilla
  • 419
  • 5
  • 16
  • I would advice you to read https://stackoverflow.com/a/46063193/1746118 the Async Variants part specifically to understand the difference. – Naman Sep 09 '17 at 13:10

1 Answers1

13

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.

thenCompose will call generateRequest() on the same thread as the upstream task (or the calling thread if the upstream task has already completed).

thenComposeAsync will call generateRequest() on the provided executor if provided, or on the default ForkJoinPool otherwise.

Joe C
  • 15,324
  • 8
  • 38
  • 50
  • possible duplicate of https://stackoverflow.com/q/46060438/1746118 in terms of the answer that the question would lead to? – Naman Sep 09 '17 at 13:13
  • I see where you're coming from, but I don't think there's enough of an overlap to really call it a duplicate. – Joe C Sep 09 '17 at 13:14