Question 2
Back to Exercise
What is the output of the following Java program?
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception {
List<Callable<Integer>> tasks = List.of(() -> 10 * 10, () -> "LearnFrenzy".length(), () -> List.of(1, 2, 3).size());
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
List<Future<Integer>> results = pool.invokeAll(tasks); // waits for ALL tasks
int sum = 0;
for (Future<Integer> f : results) sum += f.get();
System.out.println(results.size() + " " + results.stream().allMatch(Future::isDone) + " " + sum);
}
}
}
- A 3 true 114 Correct
- B 3 false 114
- C 3 true 113
- D 2 true 114
Correct Answer: Option A
invokeAll returns once every task has completed, with Futures in the same order as the tasks: 100 + 11 + 3.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!