Why does ConcurrentHashMap forbid null keys and null values, when HashMap allows them?
answer
- null = ambiguous: absent vs present-with-null
- containsKey re-check is racy under concurrency
- Both null keys AND null values throw NPE
- null is the sentinel for putIfAbsent/compute/merge
- Use Optional/sentinel instead of null
basics
~20 sBecause of an ambiguity: if get(key) returned null, you couldn't tell whether the key is absent or present with a null value. In a single thread you could re-check with containsKey, but under concurrency another thread could change the answer between calls, so nulls are banned outright.
solid answer
~40 sConcurrentHashMap throws NullPointerException on a null key or value. The reason is that null is overloaded to mean 'no mapping': get returning null could mean the key is absent or that it maps to null. In a single-threaded HashMap you disambiguate with containsKey, but in a concurrent map that two-step check is racy—another thread can insert or remove the key between get and containsKey, so the result is meaningless. Rejecting null up front gives the opposite guarantee: the class Javadoc says that because keys and values are never null, null is "a reliable atomic indicator of the current lack of any result." This also keeps the atomic methods (putIfAbsent, computeIfAbsent, merge) unambiguous, since they use null to signal 'absent' or 'remove the mapping'.
go deeper
Knows ConcurrentHashMap throws NullPointerException for null keys or values, while HashMap permits them.
Explains the absent-vs-present-with-null ambiguity and why the containsKey re-check that saves HashMap is racy under concurrency.
Connects the ban to the sentinel role null plays in putIfAbsent/compute/merge and can quote the Javadoc's payoff: with no null keys or values, a null result reliably means no result.
Discusses API-contract design implications: how disallowing nulls simplifies the atomic-method contracts and prevents whole classes of latent concurrency bugs, and recommends Optional/sentinel patterns at scale.
## The core ambiguity With any map, `get(key)` returning `null` is **ambiguous** in general: it can mean either (a) **the key is not in the map**, or (b) **the key is in the map and its value is `null`**. To tell these apart you'd call `containsKey(key)`, which returns a boolean. ## Why HashMap can live with it but ConcurrentHashMap cannot In a **single-threaded** `HashMap`, the two-step disambiguation works: ``` if (map.containsKey(k)) { // step 1 Object v = map.get(k); // step 2 } ``` Between step 1 and step 2 nothing can change the map, because only one thread is involved. In a **concurrent** map, no such guarantee exists. Between `get` (which returned `null`) and a follow-up `containsKey`, **another thread can insert or remove the key**. So the answer you compute may already be stale, and the `get`-then-`containsKey` check **cannot resolve the ambiguity**. The JDK states the reasoning in `ConcurrentSkipListMap`'s Javadoc: like most other concurrent collections it rejects nulls "because some null return values cannot be reliably distinguished from the absence of elements." `ConcurrentHashMap`'s Javadoc states the payoff, in its section on bulk operations and `get`: "because keys and values in the map are never null, null serves as a reliable atomic indicator of the current lack of any result." So the map **rejects nulls outright** with a `NullPointerException` (for both keys and values). ## Keys vs values - **Null values** are forbidden for the ambiguity reason above. - **Null keys** are also forbidden: the class does not allow null "to be used as a key or value", and `get(null)` and `containsKey(null)` throw too, where `HashMap` answers. The `containsKey` race above is an argument about values. For keys, the "never null" sentence quoted above covers them as well, and the code shows the difference: `ConcurrentHashMap` calls `key.hashCode()` directly, where `HashMap.hash` special-cases a null key to hash 0. ## It also keeps the atomic methods clean The compound atomic methods rely on `null` as a **sentinel**: - `putIfAbsent(k, v)` returns the **existing** value, or `null` if there was none (and then it inserts `v`). - `computeIfAbsent`: a mapping function that returns `null` means **"record no mapping"**, and the method returns `null`. - `compute` / `computeIfPresent` / `merge`: a remapping function that returns `null` means **"remove the mapping"**. If stored values could themselves be `null`, these sentinels would collide with real data and the methods couldn't signal "absent" vs "present-but-null" or "remove" unambiguously. Banning null values makes every one of these signals precise. ## A choice of this class, not a law of concurrency The `ConcurrentMap` interface leaves the door open: its default methods assume no null values, and "Implementations which support null values must override this default implementation." A map that allowed nulls could answer the question atomically with one call such as `getOrDefault(key, SENTINEL)`. What cannot work is the natural `get` plus `containsKey` idiom, and this class removes that trap. `Hashtable` and `ConcurrentSkipListMap` reject nulls as well. ## Practical guidance - Never pass `null` as a key or value to a CHM—you'll get an NPE, often surprisingly (e.g. `put(k, lookup())` where the lookup happens to return null, or a `replaceAll` function that returns null). - If you need to represent "known to be absent" vs "present with no value", use an explicit sentinel object or wrap in `Optional` and store the Optional, never a raw null.
- HashMap allows nulls; how many null keys can it hold?Exactly one null key (plus any number of null values). ConcurrentHashMap allows neither.
- If a computeIfAbsent mapping function returns null, what happens?No mapping is recorded and computeIfAbsent returns null. In compute/merge, returning null removes any existing mapping. That's why stored null values would clash with this sentinel.
- Saying only null values are forbidden, not null keys
- Claiming HashMap also forbids nulls (it allows one null key and null values)
- Thinking you can safely disambiguate with containsKey in a concurrent map
- Believing it's an arbitrary restriction with no rationale
context
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentMap (Java SE 27 & JDK 27)docs.oracle.com