# HashMap vs Hashtable vs ConcurrentHashMap

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

Canonical: https://www.internhack.in/learn/interview/java-interview/java-hashmap-hashtable-concurrenthashmap
Last updated: 2026-11-28

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

- HashMap is fast but not thread-safe; Hashtable uses one lock for everything.
- ConcurrentHashMap in Java 8 uses CAS for empty buckets and synchronized on the bucket head otherwise.
- CHM forbids null keys and values to avoid ambiguity under concurrency.
- CHM iterators are weakly consistent and do not throw ConcurrentModificationException.
- Use merge, compute and putIfAbsent for atomic compound operations.

## Common follow-up questions

- How did ConcurrentHashMap change between Java 7 and Java 8?
- Is containsKey followed by put safe in ConcurrentHashMap?
- What is the difference between Collections.synchronizedMap and ConcurrentHashMap?
- What is a weakly consistent iterator?

## Interview tips

- Explain the null restriction with the containsKey race. It is the answer interviewers hope to hear.
- Point out that atomic methods are per-operation; compound logic still needs merge or compute.

## Concepts covered

HashMap, Hashtable, ConcurrentHashMap, Thread Safety, CAS

Previous: [How HashMap Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashmap-internals) · Next: [How HashSet Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashset-internals) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Comparable vs Comparator and How TreeMap Sorts](https://www.internhack.in/learn/interview/java-interview/java-comparable-comparator-treemap)
- [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe)
- [Generics, Wildcards and Type Erasure](https://www.internhack.in/learn/interview/java-interview/java-generics-type-erasure)
- [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model)
- [Garbage Collection Basics and GC Roots](https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics)
- [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
