I’m probably missing something in the Guava API. How can I use ExecutorService.invokeAll with Futures.allAsList without casting?
My usecase is that I would like to submit a List of Callables and wait until all are executed (in parallel). I’m only interested in the list of results from the Callables.
ListeningExecutorService executor = MoreExecutors.sameThreadExecutor(); //or any other ExecutorService
List<Future<Object>> futures =
executor.invokeAll(singletonList(new Callable<Object>() {
@Override public Object call() throws Exception {
return 42;
}
}
));
Iterable<ListenableFuture<Object>> listableFutures =
(Iterable<ListenableFuture<Object>>) (Iterable) futures;
//would like to use "futures" here
ListenableFuture<List<Object>> r = Futures.allAsList(listableFutures);
System.out.println(r.get());
In a perfect world I would like to call ListeningExecutorService.allAsList(Collection<? extends Callable<T>> tasks) and get a Future<List<T>> or even List<T>.
Nope. You’re supposed to do the cast. It can’t be avoided, due to the way Java restricts overriding of methods.
The Javadoc for
ListeningExecutorService.invokeAllstates