Java Concurrency Interview

Concurrent collections question 68 of 180 mid

Why does ConcurrentHashMap forbid null keys and values?

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.

collections chm api

Quiz yourself on Concurrent collections Suggest a correction