CKTIS / Java
ConcurrentHashMap: atomic counter initialization and entry traversal
Use `computeIfAbsent` to initialize a `LongAdder` atomically for a missing key, then use `forEach` to read counts without depending on traversal order.
Version: Java SE 21
Syntax
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
void forEach(BiConsumer<? super K, ? super V> action)
void forEach(long parallelismThreshold, BiConsumer<? super K, ? super V> action)
<U> void forEach(long parallelismThreshold, BiFunction<? super K, ? super V, ? extends U> transformer, Consumer<? super U> action)ConcurrentHashMap.computeIfAbsent/forEach combines two jobs in java.util.concurrent.ConcurrentHashMap (Java SE 21): initializing values and visiting entries. computeIfAbsent(key, factory) atomically returns an existing value without calling the factory, or, if the key is absent, calls the factory once for that invocation, stores a non-null result, and returns it. The default Map.computeIfAbsent promises neither synchronization nor atomicity. A Map reference to a ConcurrentHashMap still calls the class's override.
The map does not accept null keys or values. A null key or factory throws NullPointerException; a null factory result is returned without creating an entry. A RuntimeException or Error from the factory propagates without creating an entry. Keep the factory short and do not modify the same map from it: other updates may have to wait, and a detected recursive update that would otherwise never finish throws IllegalStateException.
In counts.computeIfAbsent(word, k -> new LongAdder()).increment(), the counter from java.util.concurrent.atomic starts at zero. The thread-safe increment() happens after the map operation, not as part of the same atomic operation. If another thread removes or replaces the entry, the increment can hit a counter no longer in the map. sum() is exact when no thread is updating the counter, but it is not an atomic snapshot.
forEach(action) passes each key and value to the action sequentially, with no threshold. forEach(threshold, action) can use ForkJoinPool.commonPool() based on estimated map size: Long.MAX_VALUE disables parallel execution, while 1 favors maximum parallelism. A parallel action must handle shared state safely. forEach(threshold, transformer, action) passes only non-null transformation results to the action. No overload guarantees an encounter order or an atomic snapshot of the whole map during updates.
Examples
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
public class WordCounts {
private static void count(ConcurrentHashMap<String, LongAdder> counts,
String... words) {
for (String word : words) {
counts.computeIfAbsent(word, k -> new LongAdder()).increment();
}
}
public static void main(String[] args) throws InterruptedException {
var counts = new ConcurrentHashMap<String, LongAdder>();
var first = new Thread(() -> count(counts, "pear", "apple", "pear"));
var second = new Thread(() -> count(counts, "apple", "plum"));
first.start();
second.start();
first.join();
second.join();
var sorted = new TreeMap<String, Long>();
counts.forEach(Long.MAX_VALUE, (word, counter) -> sorted.put(word, counter.sum()));
sorted.forEach((word, total) -> System.out.println(word + "=" + total));
}
}Result
apple=2 pear=2 plum=1
After both `join()` calls, the counters are no longer changing. `Long.MAX_VALUE` keeps writes to the `TreeMap` sequential; the `TreeMap` sorts the output by key.
Related lessons
- Java · Lesson 24 · Advanced · Version: 2