ConcurrentHashMap in Java

ConcurrentHashMap is a thread-safe, high-performance Map that uses CAS and per-bin locking in Java 8+ to allow concurrent reads and writes without blocking.

ConcurrentHashMap<K, V> is the standard thread-safe Map implementation for concurrent applications. Unlike Hashtable (which locks the entire map on every operation), ConcurrentHashMap in Java 8+ uses compare-and-swap (CAS) for most operations and synchronizes only on individual bin heads when needed, allowing many threads to read and write simultaneously without blocking each other. It forbids null keys and null values.

How ConcurrentHashMap Achieves Thread Safety (Java 8+)

In Java 8, the segment-based locking of earlier versions was replaced with a finer-grained mechanism:

  1. Reads are almost always lock-free. The table array is declared volatile, and node values are also volatile, so a reading thread always sees the latest written value without locking.
  2. Writes (put, remove) on an empty bucket use CAS (compareAndSet) to install the first node atomically.
  3. Writes on a non-empty bucket synchronize on the head node of that bin only. This means two writes to different buckets proceed in parallel.
  4. Resize is incremental and cooperative — multiple threads can help transfer entries.
  5. Atomic compound operations (putIfAbsent, computeIfAbsent, compute, merge) are available and execute their logic atomically within the bin lock.
Property ConcurrentHashMap
Thread-safe Yes (fine-grained)
Null keys Not allowed
Null values Not allowed
Ordering Undefined
size() accuracy Approximate (uses LongAdder cells)
Iteration Weakly consistent (snapshot-like, no CME)

Time complexity is O(1) average for put, get, remove — same as HashMap.

Examples

Basic concurrent usage

import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

public class ConcurrentHashMapBasics {
    public static void main(String[] args) {
        Map<String, Integer> map = new ConcurrentHashMap<>();
        map.put("a", 1);
        map.put("b", 2);

        System.out.println(map.get("a")); // 1

        // putIfAbsent is atomic
        map.putIfAbsent("a", 99); // ignored — "a" already exists
        System.out.println(map.get("a")); // 1

        // computeIfAbsent is also atomic
        map.computeIfAbsent("c", k -> k.length()); // puts "c" -> 1
        System.out.println(map.get("c")); // 1

        // null key or value is not allowed
        // map.put(null, 1);    // NullPointerException
        // map.put("d", null);  // NullPointerException
    }
}

Concurrent word count with merge

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ConcurrentWordCount {
    public static void main(String[] args) throws InterruptedException {
        List<String> words = List.of("apple", "banana", "apple", "cherry",
                                     "banana", "apple", "date");
        Map<String, Integer> freq = new ConcurrentHashMap<>();

        // Multiple threads updating the same map safely
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (String word : words) {
            pool.submit(() -> freq.merge(word, 1, Integer::sum));
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);

        System.out.println(freq); // {apple=3, banana=2, cherry=1, date=1}
    }
}

Common Mistakes

  1. Null keys or values. ConcurrentHashMap throws NullPointerException for both. This deliberate restriction avoids ambiguity: in a concurrent context, map.get(k) == null could mean either "absent" or "value is null", making the distinction impossible without additional locking. Always ensure neither keys nor values are null before inserting.

  2. Compound check-then-act operations. Code like if (!map.containsKey(k)) map.put(k, v) is two separate operations with no atomicity guarantee — another thread can insert between them. Use putIfAbsent, computeIfAbsent, compute, or merge, which are each atomic within a single bin lock.

  3. Assuming size() is exact. ConcurrentHashMap.size() returns an approximation. It is computed from multiple LongAdder counter cells and may be slightly stale in a highly concurrent environment. If an exact count is critical, add explicit tracking.

  4. Treating iteration as strongly consistent. Iterators returned by ConcurrentHashMap are weakly consistent: they reflect the state of the map at or since the iterator was created but do not throw ConcurrentModificationException. Entries inserted after the iterator was created may or may not appear in the traversal.

  5. Using synchronized wrapper instead. Collections.synchronizedMap(new HashMap<>()) locks the entire map on every access, just like Hashtable. It does not provide atomic compound operations. Use ConcurrentHashMap instead, which is faster under concurrent load and provides the rich atomic API.

Best Practices

  • Use computeIfAbsent or putIfAbsent for all conditional inserts — never use containsKey + put as a two-step check.
  • Use merge for accumulating values concurrently (e.g., counters, aggregations).
  • Prefer ConcurrentHashMap over Collections.synchronizedMap for any concurrent workload.
  • Do not store null keys or values; restructure your data model to use a sentinel value or Optional if absence must be distinguished from presence.
  • For read-heavy workloads where the map is rarely updated after initial population, also consider Map.copyOf (immutable snapshot) or Collections.unmodifiableMap.

Interview Questions

1. How does ConcurrentHashMap achieve thread safety in Java 8+?

Java 8's ConcurrentHashMap uses a volatile table array. Reads are lock-free because both the array reference and node values are volatile. Writes to empty buckets use CAS. Writes to occupied buckets synchronize on the head node of the bin only, so concurrent writes to different buckets do not block each other. This is far more scalable than Hashtable's single lock.

2. Why does ConcurrentHashMap not allow null keys or values?

In a concurrent context, map.get(k) == null is ambiguous — it could mean the key is absent or the value is genuinely null. Distinguishing the two requires a second containsKey call, but between the two calls another thread could modify the map. Forbidding null eliminates this race condition by making absence unambiguous.

3. What is the difference between putIfAbsent and computeIfAbsent?

Both are atomic compound operations. putIfAbsent(k, v) evaluates v (the argument) before the call. computeIfAbsent(k, fn) calls fn only if the key is absent, which is important when value creation is expensive or has side effects. computeIfAbsent is also atomic within the bin — the function is called while holding the bin lock, preventing duplicate creation by racing threads.

4. How is ConcurrentHashMap different from Hashtable?

Hashtable synchronizes every method with a single lock on this, serializing all access. ConcurrentHashMap uses CAS and per-bin locking, allowing concurrent reads and writes to different bins in parallel. ConcurrentHashMap also provides atomic compound operations (putIfAbsent, computeIfAbsent, merge) that Hashtable does not. Both forbid null keys and values.

5. Is ConcurrentHashMap's size() accurate?

Not always. size() accumulates counts across multiple LongAdder cells and returns an integer. Under high concurrency, the returned value may be slightly stale. mappingCount() (Java 8+) returns a long and is preferred when the map is expected to grow beyond Integer.MAX_VALUE. For exact counts, maintain a separate AtomicLong counter.

6. Are ConcurrentHashMap iterators fail-fast?

No. They are weakly consistent — they do not throw ConcurrentModificationException. Iterators reflect the state of the map at some point at or since the iterator was created. Entries inserted or removed after iterator creation may or may not appear in the traversal. This is safe but means you should not rely on iteration to capture a complete snapshot.

7. When would you use Collections.synchronizedMap instead of ConcurrentHashMap?

Almost never. Collections.synchronizedMap wraps a HashMap with a single mutex, producing semantics similar to Hashtable — one thread at a time. It does not provide atomic compound operations. The only scenario where it might be preferred is when you need guaranteed sequential consistency for iteration with an explicit synchronized block around the iteration, and you find the semantics of ConcurrentHashMap too relaxed for a specific use case.

Summary

  • ConcurrentHashMap uses CAS on empty bins and per-bin synchronized blocks on occupied bins for high-concurrency writes with no global lock.
  • Reads are lock-free thanks to volatile fields.
  • null keys and null values are forbidden to avoid ambiguity in concurrent lookups.
  • Use atomic methods (computeIfAbsent, putIfAbsent, merge) for compound operations — never a manual check-then-put.
  • Iteration is weakly consistent and will not throw ConcurrentModificationException.

Continue Learning

Previous: Hashtable | Next: Comparable

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.