Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

The ConcurrentHashMap class

Reference for java.util.concurrent.ConcurrentHashMap: thread-safe map operations, atomic merge/compute, bulk operations, null rules and pitfalls.

ConcurrentHashMap<K,V> is a hash table that many threads can read and update at the same time. Reads do not lock, and writes lock only a small part of the table, so it scales far better than Collections.synchronizedMap() or the legacy Hashtable. It is the default shared map in Java.

Each single call is atomic and thread-safe, and the class adds atomic compound operations (putIfAbsent, compute, computeIfAbsent, merge) so you do not have to write check-then-act sequences yourself. Iterators are weakly consistent: they never throw ConcurrentModificationException.

Java
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge("apple", 1, Integer::sum);     // atomic increment

Try it

Java Atomic updates from several threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Nulls, bulk operations and key sets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
        implements ConcurrentMap<K,V>, Serializable
Constructor Description
ConcurrentHashMap() Default capacity (16).
ConcurrentHashMap(int initialCapacity) Sized for about that many entries.
ConcurrentHashMap(Map<? extends K,? extends V> m) Copy of another map.
ConcurrentHashMap(int cap, float loadFactor, int concurrencyLevel) Sizing hints; concurrencyLevel is only a hint.
Method Description
V putIfAbsent(K, V) Stores if absent; returns the previous value or null.
V computeIfAbsent(K, Function) Computes and stores a value if absent, atomically.
V compute(K, BiFunction), computeIfPresent Atomic update; returning null removes the entry.
V merge(K, V, BiFunction) Inserts the value or combines it with the existing one.
boolean remove(K, V), replace(K, old, new) Conditional removal and replacement.
long mappingCount() Entry count as a long; preferred over size().
forEach, search, reduce (with a parallelism threshold) Bulk operations on entries, keys or values.
static <T> KeySetView<T,Boolean> newKeySet() A concurrent Set.

Usage notes

  • No null keys or values. get(k) == null unambiguously means "absent". Use Optional or a sentinel for "present but empty".
  • Compound actions need the compound methods. containsKey followed by put is a race; use putIfAbsent, computeIfAbsent or merge.
  • Keep compute functions short and side-effect free. They run while the bin is locked; they must not update the same map (that can deadlock or throw IllegalStateException) and should not do slow I/O.
  • size() and isEmpty() are estimates while other threads update the map; the result is exact once activity stops.
  • Iteration is weakly consistent: it reflects the map at some point at or after creation, and does not fail when the map changes.
  • Iteration order is unspecified. Sort or copy into a TreeMap before printing.
  • Performance: reads are lock-free; writes to different bins proceed in parallel. Since Java 8 heavily collided bins become trees.
  • A ConcurrentHashMap does not make its values thread-safe. A mutable ArrayList stored as a value still needs its own protection.
  • Sorted alternative: ConcurrentSkipListMap. For single-threaded code a plain HashMap is faster.