ConcurrentHashMap Atomic Aggregation
Aggregate concurrent increments with ConcurrentHashMap compute and merge so counter updates stay atomic without external locking.
Code
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class WordCountConcurrent {
public static void main(String[] args) throws InterruptedException {
List<String> lines = List.of(
"event=login user=alice",
"event=login user=bob",
"event=purchase user=alice",
"event=view user=carol",
"event=login user=alice");
ConcurrentHashMap<String, Integer> eventCounts = new ConcurrentHashMap<>();
// 多线程并发提交:compute 对同一 key 原子执行,无需 synchronized
Thread worker1 = Thread.ofPlatform().start(() -> aggregate(lines.subList(0, 3), eventCounts));
Thread worker2 = Thread.ofPlatform().start(() -> aggregate(lines.subList(3, 5), eventCounts));
worker1.join();
worker2.join();
// merge 同样原子: absent → value, present → remapping
eventCounts.merge("event=login", 100, Integer::sum);
eventCounts.forEach((event, count) -> System.out.println(count + " " + event));
}
private static void aggregate(List<String> chunk, ConcurrentHashMap<String, Integer> counts) {
for (String line : chunk) {
String event = line.split(" ")[0];
counts.compute(event, (key, known) -> known == null ? 1 : known + 1);
}
}
}Inside the snippet
ConcurrentHashMap Atomic Aggregation comes down to the class WordCountConcurrent and the function aggregate.
Repetition is confined to for (String line : chunk) — the rest of the file is straight-line.
Putting it to use
The entry-point signature is private static void aggregate(List<String> chunk, ConcurrentHashMap<String, Integer> counts)
Launch the file; main takes over and steps through aggregate.
Core lines
Thread worker1 = Thread.ofPlatform().start(() -> aggregate(lines.subList(0, 3), eventCounts));
Thread worker2 = Thread.ofPlatform().start(() -> aggregate(lines.subList(3, 5), eventCounts));
Interactive Tools for This Topic
FAQ
- How do you run ConcurrentHashMap Atomic Aggregation?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.