Getting a list of results from a list of CompletableFutures

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Getting a list of results from a list of CompletableFutures

Mike Axiak

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 = -> {
try {
} catch (Exception e) {
return e;
return null;
if (exceptions.isEmpty()) {
result.complete( -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} 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;


Concurrency-interest mailing list
[hidden email]