LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 2

invokeAll with a list of Callables Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Java program?

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

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links