Concurrent collections question 68 of 180 mid
Why does ConcurrentHashMap forbid null keys and values?
- An oversight kept for compatibility
- Correct: Because
getreturning null would be ambiguous, and with concurrent writers you cannot resolve it withcontainsKey - Because null cannot be hashed
- Because it would break serialisation
In a HashMap, get(k) == null is ambiguous between "absent" and "mapped to null", and you resolve
it with containsKey. In a concurrent map that second call is a separate point in time: the mapping
can appear or vanish in between, so the ambiguity cannot be resolved at all. Doug Lea's position is
that allowing null buys nothing and hides bugs.
The practical follow-up is computeIfAbsent returning null from the mapping function, which means "do
not store anything", not "store null". And merge treats a null result as a removal. Both surprise
people porting code from HashMap.
Quiz yourself on Concurrent collections Suggest a correction