Reputation: 2020
I have the following code:
class SomeClass {
private Map<String, String> someMap = null;
public String getValue(String key) {
if (someMap == null) {
someMap = initialize(); // initialize() is some method which returns a proper map.
}
return someMap.get(key);
}
}
Assuming I don't care about someMap
getting initialized more than once, are there any other thread-safety issues that I need to be concerned about here.
As per what-operations-in-java-are-considered-atomic , Reference assignment is certainly atmoic. Is the assignment to someMap
guaranteed to happen after the method call to initialize()
(seems logical to me). Is there any possibility that a thread can see a partially constructed someMap
. Does it matter if instead of a map, I have some other type of object.
Upvotes: 1
Views: 71
Reputation: 2006
Its not a Thread Safe even if you put volatile because if two threads are called getValue method at a same time, the following scenario can happen
1) Thread 1 & Thread 2 check if (someMap == null) , both will pass and try to reinitialise.
2) Both will reinitialize the reference. Thread 1 return the old reference which one is override by thread 2 .
3) So please refer the link Double Checked Locking in Singleton
Upvotes: 0
Reputation: 50044
The code is not thread-safe. If two threads invoke the method getValue
on the same object, it is possible, that one thread sees a partially created someMap
.
In order to avoid this problem, you have to remove the data races. The simplest solution is to declare someMap
as volatile
. The simple rule to remember is: If the code contains no data races, then all executions will appear to be sequentially consistent.
Upvotes: 4