Card 04/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
What Future.get() Does to the Thread That Calls It
Four tasks submitted to a pool and four results collected. The whole thing takes as long as the slowest one, or as long as all four put together, depending on where one line goes.
for (Path file : files) {
long rows = pool.submit(() -> countRowsIn(file)).get();
total += rows;
}get() blocks: the calling thread stops until the result is ready. Calling it in the same statement as submit means nothing is ever submitted while something else is running.
List<Future<Long>> futures = files.stream()
.map(f -> pool.submit(() -> countRowsIn(f)))
.toList();
for (Future<Long> f : futures) {
total += f.get();
}Submit everything first, then collect. All four tasks are queued before any result is wanted, so the pool can run them at once and the waiting happens at the end.
So submit and get are two halves of one operation and belong at two ends of the code. Putting them on one line turns a pool back into a sequence.