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?
Null is not allowed for both key and value.
HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.
Inserting null objects is not possible in ConcurrentHashMap as a key or value.
A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It contains only unique elements. It cannot have null key but can have multiple null values.
The Map returned by Collections.synchronizedMap supports all of the features of the Map you give it. If you give it a HashMap, it supports the null key (and also null 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:
import java.util.*;
public class MapTest
{
public static final void main(String[] args)
{
Map map;
try
{
map = Collections.synchronizedMap(new HashMap());
map.put("one", "a");
System.out.println("Size = " + map.size());
map.put(null, "b");
System.out.println("Size = " + map.size());
System.out.println("map.get(null) = " + map.get(null));
}
catch (Exception ex)
{
System.out.println("Exception: " + ex.getMessage());
ex.printStackTrace(System.out);
}
System.exit(0);
}
}
Output:
Size = 1 Size = 2 map.get(null) = b
As far as I know there is neither a simple way to make ConcurrentHashMap nor an equivalent class supporting null keys or values.
ConcurrentHashMap is quite different from Collections.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 Iterators returned by a synchronized map are prone to throw ConcurrentModificationException if the underlying map is modified while using the iterator. On the other hand, the ConcurrentHashMap iterators' are guaranteed to never throw ConcurrentModificationException even if the underlying map is changed while using the iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With