Java Reference
In-Depth Information
List<Integer> requestedIds =
futures.stream().flatMap(future ->
get(future).stream()).distinct()
.collect(Collectors.toList()); // [4]
logger.info(requestedIds.toString());
} catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
private List<Integer> get(Future<List<Integer>> future)
{
try {
return future.get();
} catch (InterruptedException | ExecutionException
e) {
logger.log(Level.SEVERE, e.getMessage(), e);
return new ArrayList<>();
}
}
}
We start by obtaining an instance of
ManagedExecutorService
using the
@Re-
source
annotation
[1]
. Next, the previously created tasks are injected using the CDI's
Instance<T>
class pattern
[2]
. Thanks to this, the are managed beans and have their
dependencies injected. With the dependencies in place, we use the
invokeAll
method
[3]
of
executorService
in order to start all our tasks at once (we could also use
multiple calls of the
submit
method). The return values represent a set of future results,
which can be used to retrieve the collected data when it is ready.
At this point, our tasks are already running so we can simply make a blocking
get
call on
the future results and wait for the data
[4]
. When it is ready, we remove any duplicates,
and collect the results in a single list using the
flatMap
operation. As you remember,
our previous two tasks were waiting 5 seconds each. Thanks to the fact that they are ex-
ecuted simultaneously, we expect that they will both finish after 5 seconds.