开发者

Thread-safe map with null-key capability

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 a开发者_开发百科ccept 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


As far as I know there is neither a simple way to make ConcurrentHashMap nor an equivalent class supporting null keys or values.

ConcurrentHashMap is quite different from Collections.synchronizedMap(new HashMap()).

First of all because a synchronized map will prevent any concurrent accesses to happen simultaneously even if all accesses are read only. ConcurrentHashMap won't block concurrent read accesses and, in some cases, may even accept concurrent writes.

But the more important thing is that the Iterators returned by a synchronized map are prone to throw ConcurrentModificationException if the underlying map is modified while using the iterator. On the other hand, the ConcurrentHashMap iterators' are guaranteed to never throw ConcurrentModificationException even if the underlying map is changed while using the iterator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜