Java hashmap只读线程安全 [英] Java hashmap readonly thread safety

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

问题描述

我有这段代码具有在静态块中初始化的共享哈希图.我不公开哈希图,它是只读的(get和containKey). 我想确定这是否是线程安全的.

I have this code that has a shared hash map initialized in static block. I don't expose the hashmap and it's used read-only (get and containKey). I wanted to make sure if this is thread-safe.

public class MyClass {
    private static final Map<String, MyObject> myMap;

    static {
        myMap = new MyLoader().load()
    }

    public MyClass() {
        if (containsKey(someKey)) {
           // do something
        }
        myMap.get(something)
    }

    static boolean containsKey(String key) {
        // do some other stuff
        return myMap.containsKey(key)
    }
}

推荐答案

假定new MyLoader().load()返回的映射完全用所有数据初始化,此后再也不会修改,那么所有线程检索数据都是安全的从此地图同时进行. HashMap的Javadoc说:如果多个线程同时访问一个哈希映射,并且至少有一个线程在结构上修改该映射,则必须在外部进行同步."因此,如果没有线程在修改映射,则不必同步.

Assuming that new MyLoader().load() returns a map that is completely initialized with all data and which is never modified after that, then it is safe for all threads to retrieve data from this map concurrently. The Javadoc for HashMap says: "If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally." Therefore, if no thread is modifying the map, then it doesn't have to be synchronized.

为安全起见,您的load()方法应强制执行不变性:

As a safety measure, your load() method should enforce immutability:

public Map<String, MyObject> load() {
    Map<String, MyObject> mymap = new HashMap<>();
    mymap.put(...);
    ...
    return Collections.unmodifiableMap(mymap);
}

这样,您不必担心您不熟悉的某些代码中的某些线程可能会无意间修改了地图.它将无法.

This way, you don't have to worry that some thread in some code you're unfamiliar with might inadvertently modify the map. It won't be able to.

这篇关于Java hashmap只读线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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