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
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

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest