HashMap vs Hashtable vs ConcurrentHashMap

Difficulty: Advanced

Question

Compare HashMap, Hashtable and ConcurrentHashMap. How does ConcurrentHashMap achieve thread safety, and why doesn't it allow nulls?

Answer

This question is really about one idea: how do you share a map between threads safely without making everything slow? The three classes are three different answers, so let me take them in historical order.

HashMap, introduced in Java 1.2, is not thread-safe at all. It is fast and allows one null key and any number of null values. If multiple threads modify it at once, you can lose updates or corrupt the structure. Use it when the map is confined to a single thread or is effectively read-only after construction.

Hashtable, from Java 1.0, is the original thread-safe map. It makes every method synchronized, so there is a single lock on the whole table. Only one thread can operate on it at any moment, even if they touch different keys, which kills scalability. It does not allow null keys or values, extends the legacy Dictionary class, and its enumerators are not fail-fast in the same way. Nobody writes new code with Hashtable. The Collections.synchronizedMap wrapper has the same one-big-lock problem, and iterating over it still requires manual synchronization.

ConcurrentHashMap (CHM) is the modern answer. In Java 7 it used segment locking: the map was split into 16 segments, each with its own lock, so up to 16 threads could write simultaneously. In Java 8 it was redesigned and dropped segments. Now it uses the same table-of-buckets structure as HashMap, with two techniques. When inserting into an empty bucket, it uses a lock-free CAS (compare-and-swap) operation. When the bucket already has nodes, it uses synchronized on just the first node of that bucket. So the lock granularity is a single bucket. Reads are generally lock-free thanks to volatile fields, and the size counter uses a striped approach similar to LongAdder. Treeification of long chains works as in HashMap.

Why no nulls in CHM? Because in a concurrent setting, the value null from get would be ambiguous. In a plain HashMap you can call containsKey to distinguish a missing key from a key mapped to null. In a CHM another thread could insert or remove the key between your two calls, so the answer might be wrong. Banning null makes get(key) == null mean definitely absent. Doug Lea, the author, made this design decision explicitly.

Iterators in CHM are weakly consistent, not fail-fast. They never throw ConcurrentModificationException and may or may not reflect updates made after the iterator was created. Methods like size are estimates in the presence of concurrent updates.

Important nuance: individual operations are atomic, but compound check-then-act sequences are not. Writing if (!map.containsKey(k)) map.put(k, v) is a race condition. Use the atomic methods putIfAbsent, computeIfAbsent, compute and merge instead. For counters, map.merge(word, 1, Integer::sum) is the idiom.

Summary for the interview: HashMap for single-threaded speed, ConcurrentHashMap for concurrent access, Hashtable and synchronizedMap for legacy only.

Code examples

Null handling differences

import java.util.*;
import java.util.concurrent.*;

public class NullDemo {
    public static void main(String[] args) {
        Map<String, String> hm = new HashMap<>();
        hm.put(null, "x");
        System.out.println(hm.get(null));

        try {
            new Hashtable<String, String>().put("k", null);
        } catch (NullPointerException e) {
            System.out.println("Hashtable NPE");
        }
        try {
            new ConcurrentHashMap<String, String>().put("k", null);
        } catch (NullPointerException e) {
            System.out.println("ConcurrentHashMap NPE");
        }
    }
}

Only HashMap tolerates null keys and values.

Atomic counting with merge

import java.util.concurrent.*;

public class CounterDemo {
    public static void main(String[] args) throws Exception {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                map.merge("hits", 1, Integer::sum);
            }
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(map.get("hits"));
    }
}

merge is atomic, so no increments are lost. A get-then-put sequence in place of merge could lose updates.

Key points

Common follow-up questions

Interview tips

Concepts covered

HashMap, Hashtable, ConcurrentHashMap, Thread Safety, CAS

More Core Java & Collections questions