javaconcurrenthashmap

Why does ConcurrentHashMap prevent null keys and values?


The JavaDoc of ConcurrentHashMap says this:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

My question: Why?

2nd question: Why doesn't Hashtable allow null?

I've used a lot of HashMaps for storing data. But when changing to ConcurrentHashMap I got several times into trouble because of NullPointerExceptions.


Solution

  • From the author of ConcurrentHashMap himself (Doug Lea):

    The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.