具有零键function的线程安全映射

我需要一个multithreadingMap对象在我的Web服务器的缓存中使用,我需要null键。

HashMap允许我使用null键,但ConcurrentHashMap不允许。 我尝试使用Collections.synchronizedMap(new HashMap())创建HashMap的同步版本,但它也不接受null键。

有没有我可以使用的替代品,而不必实现某种方式来包装null键?

Collections.synchronizedMap返回的Map支持您提供的Map所有function。 如果你给它一个HashMap ,它支持null键(也是null值,你说“……我需要”null“键值……”可以读取任何一种方式)。 是什么让你觉得它没有?

这按预期工作,例如:

 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); } } 

输出:

 大小= 1
大小= 2
 map.get(null)= b 

据我所知,既没有简单的方法来创建ConcurrentHashMap也没有一个支持null键或值的等效类。

ConcurrentHashMapCollections.synchronizedMap(new HashMap())完全不同。

首先,因为同步映射将阻止任何并发访问同时发生,即使所有访问都是只读的。 ConcurrentHashMap不会阻止并发读取访问,在某些情况下,甚至可能接受并发写入。

但更重要的是,如果在使用迭代器时修改了底层映射,则由同步映射返回的Iterator很容易抛出ConcurrentModificationException 。 另一方面,即使在使用迭代器时更改了基础映射,也保证ConcurrentHashMap迭代器永远不会抛出ConcurrentModificationException