I have a list of futures.
List<Future> futures = new ArrayList<Future>();
futures.add(task1());
futures.add(task2());
Is there a difference between these two approaches of getting the results?
// Option 1
for (Future future : futures) {
results.add(future.get());
}
// Option 2
boolean incompleteFound;
do {
incompleteFound = false;
for (Future future : futures) {
if (!future.isDone()) {
incompleteFound = true;
}
}
} while (incompleteFound);
for (Future future : futures) {
results.add(future.get());
}
I would assume in Option 1
while the get
call is blocking, this wouldn't affect the processing of the futures in the background. Am I correct in that assumption?
Correct. Do the first one. Waiting for one future's result won't affect any of the others (nor even the one you're waiting on).
The second one is not only unnecessary but also super wasteful. Instead of yielding the CPU to other threads you now have a busy loop that'll spin the CPU consuming CPU cycles for no reason.