ConcurrentHashMap
A thread-safe map for concurrent use from many threads.
Available since: Java 1.5
Syntax
public class ConcurrentHashMap<K, V> implements ConcurrentMap<K, V>Examples
Counting words from several threads:
void main() {
var counts = new ConcurrentHashMap<String, Integer>();
List<String> words = List.of("a", "b", "a", "c", "a", "b");
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int round = 0; round < 100; round++) {
for (String w : words) {
executor.submit(() -> counts.merge(w, 1, Integer::sum));
}
}
}
IO.println(new TreeMap<>(counts));
}Output:
{a=300, b=200, c=100}Notes
Individual methods are safe, but compound actions must be one atomic call: merge(), compute(), computeIfAbsent(), putIfAbsent(). A get() + put() pair from different threads loses updates. null keys and values are forbidden.
See also
- HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
- Map.merge() — Adds a value under a key or combines it with the existing one.
- AtomicInteger — An integer that can be changed safely from several threads without locks.
Related recipes
In the tutorial
- Concurrent collections — Collections for multithreaded code in Java — ConcurrentHashMap and merge, CopyOnWriteArrayList, BlockingQueue and the producer-consumer pattern.