我需要一个多线程 Map 对象用于我的网络服务器缓存,并且我需要有 null
键。
HashMap
允许我使用空键,但 ConcurrentHashMap
不允许。我尝试使用 Collections.synchronizedMap(new HashMap())
创建 HashMap
的同步版本,但它也不接受 null
键。
有没有我可以使用的替代方案,而不必实现某种方式来包装 null
键?
最佳答案
Collections.synchronizedMap
返回的 Map
支持您提供的 Map
的所有功能。如果你给它一个 HashMap
,它支持 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);
}
}
输出:
Size = 1 Size = 2 map.get(null) = b
关于java - 具有空键功能的线程安全映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5699794/