I call a method that returns a Future
, once for each element in a List<Principal>
, so I end up with a List<Future<UserRecord>>
.
The method returning Future
is library code and I have no control over how that code gets run, all I have is the Future
.
I want to wait for all the Future
s to finish (success or failure) before proceeding further.
Is there a better way to do so than this:
List<Principal> users = new ArrayList<>();
// Fill users
List<Future<UserRecord>> futures = getAllTheFutures(users);
List<UserRecord> results = new ArrayList<>(futures.size());
boolean[] taskCompleted = new boolean[futures.size()];
for (int j = 0; j < taskCompleted.length; j++) {
taskCompleted[j] = false;
}
do {
for (int i = 0; i < futures.size(); i++) {
if (!taskCompleted[i]) {
try {
results.add(i, futures.get(i).get(20, TimeUnit.MILLISECONDS));
taskCompleted[i] = true;
} catch (TimeoutException e) {
// Do nothing
} catch (InterruptedException | ExecutionException e) {
// Handle appropriately, then...
taskCompleted[i] = true;
}
}
}
} while (allNotCompleted(taskCompleted));
For the curious:
private boolean allNotCompleted(boolean[] completed) {
for (boolean b : completed) {
if (!b)
return true;
}
return false;
}
Unlike in this answer to Waiting on a list of Future I don't have control over the code that creates the Future
s.