[concurrency-interest] Getting a list of results from a list of CompletableFutures

Mike Axiak mike at axiak.net
Mon Mar 23 15:11:30 EDT 2015


Hi,

I love the CompletableFuture API, and I understand the signature for
anyOf(), but I don't quite understand why allOf()'s interface is so
limited. Am I missing something, or could the following work:

    public static <T> CompletableFuture<List<T>>
allOf(Collection<CompletableFuture<? extends T>> futures) {
      CompletableFuture<List<T>> result = new CompletableFuture<>();
      CompletableFuture<Void> impl =
CompletableFuture.allOf(futures.toArray(new
CompletableFuture[futures.size()]));
      impl.thenAccept((v) -> {
        List<Exception> exceptions =
futures.stream().filter(CompletableFuture::isCompletedExceptionally).map((future)
-> {
          try {
            future.getNow(null);
          } catch (Exception e) {
            return e;
          }
          return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
          if (exceptions.isEmpty()) {
          result.complete(futures.stream().map((future) -> {
            try {
              return future.get();
            } catch (InterruptedException | ExecutionException e) {
              throw new RuntimeException(e);
            }
          }).collect(Collectors.toList()));
        } else {
          impl.completeExceptionally(new MultiFutureException(exceptions));
        }
      });
      return result;
    }
        public static class MultiFutureException extends Exception {
      private final List<Exception> exceptionsCauses;
        public MultiFutureException(List<Exception> exceptionsCauses) {
        this.exceptionsCauses = exceptionsCauses;
      }
    }

Best,
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20150323/fcd4c84a/attachment.html>


More information about the Concurrency-interest mailing list