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.
allNotCompleted(taskCompleted)
snippet check entire array and return an overall result ? – Mouleget()
? What purpose does it serve since you'll keep looping back to it. Also, what does "Handle appropriately" mean in your context, as it affects a lot on what the code needs to do and can do. You're new to Java aren't you? You're initializing yourboolean[]
to false, even though it's the default. – Taskerresults
list contain anull
for elementi
as that means failure to get a valid result. In other places in my code "Handle appropriately" may mean something different. Don't see how that is relevant to waiting for all Futures to finish (one way or another). Yeah, I guess I could do without a timeout onget()
. – Feathercutfor (Future<UserRecord> future : futures) results.add(future.get());
? – Douzepers