Null Key Streaming Card

I need a multi-threaded Map object for use in caching a web server, and I need to have null keys.

HashMap allows me to have null keys, but ConcurrentHashMap does not. I tried to create a synchronized version of HashMap using Collections.synchronizedMap(new HashMap()) , but it does not accept null keys.

Is there any alternative I can use without having to wrap null keys in any way?

+4
source share
2 answers

Map returned by Collections.synchronizedMap supports all the Map functions that you give it. If you give it a HashMap , it supports the null key (as well as null values, you said "... I need to have" key values ​​"..." that can be read anyway), which makes you think that this is not So?

This works as expected, for example:

 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 
+6
source

As far as I know, there is no easy way to make a ConcurrentHashMap or equivalent class that supports null keys or values.

ConcurrentHashMap very different from Collections.synchronizedMap(new HashMap()) .

First of all, because a synchronized card will prevent simultaneous simultaneous access at the same time, even if all calls are read-only. ConcurrentHashMap will not block concurrent read access and, in some cases, may even accept concurrent writes.

But all the more important, the Iterator returned by the synchronized map is prone to throwing a ConcurrentModificationException if the basemap changes when using an iterator. ConcurrentHashMap iterators, on the other hand, are guaranteed to never throw a ConcurrentModificationException , even if the basemap changes when using an iterator.

+2
source

All Articles