I need a multi-threaded Map object to use in my web server's caching, and I need to have null
keys.
HashMap
allows me to have null keys, but ConcurrentHashMap
doesn't. I tried to create a synchronized version of HashMap
using Collections.synchronizedMap(new HashMap())
but it doesn't accept null
keys either.
Is there any alternative that I can use, without having to implement some way to wrap the null
keys?
The
Map
returned byCollections.synchronizedMap
supports all of the features of theMap
you give it. If you give it aHashMap
, it supports thenull
key (and alsonull
values, you said "...I need to have "null" key values..." which can be read either way). What makes you think it doesn't?This works as expected, for instance:
Output:
As far as I know there is neither a simple way to make
ConcurrentHashMap
nor an equivalent class supportingnull
keys or values.ConcurrentHashMap
is quite different fromCollections.synchronizedMap(new HashMap())
.First of all because a synchronized map will prevent any concurrent accesses to happen simultaneously even if all accesses are read only.
ConcurrentHashMap
won't block concurrent read accesses and, in some cases, may even accept concurrent writes.But the more important thing is that the
Iterator
s returned by a synchronized map are prone to throwConcurrentModificationException
if the underlying map is modified while using the iterator. On the other hand, theConcurrentHashMap
iterators' are guaranteed to never throwConcurrentModificationException
even if the underlying map is changed while using the iterator.