[concurrency-interest] Handling Null Values in ConcurrentHashMap

Doug Lea dl at cs.oswego.edu
Fri May 12 08:02:32 EDT 2006

Tutika Chakravarthy wrote:
> Hi ,
> I would like to replace some Hashmaps in our
> application, which are prone to multi threading issues
> with ConCurrentHashMap.
> Currently we keep null key and values in hashmap
> without any issues as HashMap allows them.
> But ConcurrentHashMap does not allow any null key and
> values .

Try to take Holger's advice. As mostly an aside though...

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.

Further digressing: I personally think that allowing
nulls in Maps (also Sets) is an open invitation for programs
to contain errors that remain undetected until
they break at just the wrong time. (Whether to allow nulls even
in non-concurrent Maps/Sets is one of the few design issues surrounding
Collections that Josh Bloch and I have long disagreed about.)

> It is very difficult to check for null keys and values
> in my entire application .

Would it be easier to declare somewhere
   static final Object NULL = new Object();
and replace all use of nulls in uses of maps with NULL?


More information about the Concurrency-interest mailing list