Card 04/ 09

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.

java
for (Path file : files) {
    long rows = pool.submit(() -> countRowsIn(file)).get();
    total += rows;
}
submits one and waits for it before submitting the next — no overlap at all

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.

java
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.