Java hashmap readonly thread safety

久未见 提交于 2020-01-01 12:09:38

问题


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)
    }
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/42380668/java-hashmap-readonly-thread-safety

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!