codereviewanskquestions
codereviewanskquestions

Reputation: 13998

Java hashmap readonly thread safety

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

Upvotes: 12

Views: 11611

Answers (1)

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11631

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.

Upvotes: 15

Related Questions