[concurrency-interest] CompletableFuture in Java 8

Millies, Sebastian Sebastian.Millies at softwareag.com
Mon Dec 1 10:38:55 EST 2014



> -----Original Message-----
> From: concurrency-interest-bounces at cs.oswego.edu [mailto:concurrency-interest-
> bounces at cs.oswego.edu] On Behalf Of Doug Lea
> Sent: Monday, December 01, 2014 2:59 PM
> To: concurrency-interest
> Subject: Re: [concurrency-interest] CompletableFuture in Java 8
>
[snip]

> This is the model we had in mind with CompletionStage:
> It doesn't include any way of getting or setting or waiting for results, so is a
> preferable return type for most user-level methods in layered frameworks.

[snip]

Perhaps this is somewhat at a tangent, but why are allOf(), anyOf() not in CompletionStage ?
They don't wait, do they?

Example: Tomasz Nurkiewicz has proposed the following
code for aggregating the results of multiple CompletableFutures in a List:

  /**
   * We'd like to utilize existing CompletableFuture.allOf(). Unfortunately, it has two minor drawbacks - it takes
   * vararg instead of Collection and doesn't return a future of aggregated results but Void instead. By aggregated
   * results I mean: if we provide List<CompletableFuture<Double>>, it should return CompletableFuture<List<Double>>,
   * not CompletableFuture<Void>! Luckily it's easy to fix with a bit of glue code.
   */
  public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
    // the trick is to use existing allOf() but when allDoneFuture completes (which means all/ underlying futures are done),
    // simply iterate overall futures and join() (blocking wait) on each. However this call is guaranteed not to block because
    // by now all futures completed!
    CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures
        .size()]));
    return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(toList()));
  }

Would it not be nicer if this method could be called with List<CompletionStage> argument (of course also returning a
CompletionStage)? I find myself inserting map(s->s.toCompletionStage()) in my streams in order to call this
method, and then continue working with CompletionStage methods (thenApply() etc.) on the "aggregated" result.

I'd like to avoid CompletableFuture showing up in the types of the intermediate variables. Is there a way?

Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com




More information about the Concurrency-interest mailing list