问题描述
我需要一个多线程的Map对象用于我的Web服务器的缓存,我需要 由 code>值,你说的是...我需要有null键值......可以读取任何一种方式)。是什么让你觉得它没有?
这可以按预期工作,例如:
import java.util。*;
public class MapTest
{
public static final main(String [] args)
{
Map map;
尝试
{
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);
$ / code $ / pre
$ b $输出:
尺寸= 1
尺寸= 2
map.get(null)= b
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 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
这篇关于具有空键功能的线程安全映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!