I have a java thread safe map which stores String to Object mappings:
ConcurrentHashMap<String, MyObject> map = new ConcurrentHashMap<>();
Here MyObject is a user defined class. Now consider the following method:
public void replace(String key, MyObject o) {
MyObject m = map.get("somekey");
synchronized(m) {
// Modify some internal components of m
// and some other objects related to m
}
}
My intention here is I want to maximise performance by not putting a lock on the whole class but only on threads that try to access the same key in the map. Basically every time an entry is replaced in the map (not added) this part of the code gets executed. Something like:
public void put(String key, MyObject o) {
if (map.putIfAbsent(key, o) == null){ //do something
}
else {
replace(key, o);
}
}
For all practical purposes we can assume that this is the only method through which a reference to MyObject can be changed. Is this implementation thread safe?