LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 13

Concurrent word counting with ConcurrentHashMap Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        List<String> lines = List.of("a b a", "b c", "a c c", "b");
        ConcurrentHashMap<String, Integer> freq = new ConcurrentHashMap<>();
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            for (String line : lines) pool.submit(() -> { for (String w : line.split(" ")) freq.merge(w, 1, Integer::sum); });
        }
        System.out.println(new TreeMap<>(freq) + " " + freq.reduceValues(1, Integer::sum));
    }
}
  • A {a=3, b=3, c=3} 9 Correct
  • B {a=3, b=3, c=3} 3
  • C {a=2, b=3, c=3} 8
  • D It varies
Correct Answer: Option A

merge is atomic per key, so no counts are lost; reduceValues adds all values (a parallelism threshold of 1 is allowed).

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