The JavaDoc of ConcurrentHashMap
says this:
Like
Hashtable
but unlikeHashMap
, this class does not allownull
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.
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)
returnsnull
, you can't detect whether the key explicitly maps tonull
vs the key isn't mapped. In a non-concurrent map, you can check this viamap.contains(key)
, but in a concurrent one, the map might have changed between calls.