具有空键功能的线程安全映射 [英] Thread-safe map with null-key capability

查看:161
本文介绍了具有空键功能的线程安全映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个多线程的Map对象用于我的Web服务器的缓存,我需要 null 键。



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



是否有其他替代方法可以使用,而不必实现某种方式来包装 null 键?

解决方案 Collections.synchronizedMap 支持您给它的 Map 的所有功能。如果你给它一个 HashMap ,它支持 null 键(还有 null 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

这篇关于具有空键功能的线程安全映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆