Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 872
codereviewanskquestions Avatar asked Feb 22 '17 00:02

codereviewanskquestions


People also ask

Is HashMap thread-safe in Java?

HashMap is non-synchronized. It is not thread-safe and can't be shared between many threads without proper synchronization code whereas Hashtable is synchronized.

How do you make a HashMap method thread-safe?

You can make HashMap thread safe by wrapping it with Collections. synchronizedMap() .

Is reading thread-safe Java?

Important points about Thread-Safety in Java Since String is immutable in Java, it's inherently thread-safe. 2) Read-only or final variables in Java are also thread-safe in Java.

Is ConcurrentHashMap slower than HashMap?

HashMap, Hashtable, ConcurrentHashMap performance comparison If you notice ConcurrentHashMap is slightly slower performing than HashMap, however it's a 100% thread safe implementation. On the other hand Hashtable is also thread safe implementation, but it's 18 times slower than HashMap for this test scenario.


1 Answers

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.

like image 176
Klitos Kyriacou Avatar answered Sep 22 '22 21:09

Klitos Kyriacou