Can anyone tell me whether this class is threadsafe or not ?
class Foo {
private final Map<String,String> aMap;
public Foo() {
aMap = new HashMap<String, String>();
aMap.put("1", "a");
aMap.put("2", "b");
aMap.put("3", "c");
}
public String get(String key) {
return aMap.get(key);
}
}
Edit: It my fault to not clarify the question. According to JMM FAQ :
A new guarantee of initialization safety should be provided. If an object is properly constructed (which means that references to it do not escape during construction), then all threads which see a reference to that object will also see the values for its final fields that were set in the constructor, without the need for synchronization.
This made me confuse that the set to aMap is aMap = new HashMap<String, String>();
. So other threads can see these
aMap.put("1", "a");
aMap.put("2", "b");
aMap.put("3", "c");
or not ?
Edit: I found this question that exactly closed to my question
As already pointed out it's absolutely thread-safe, and final
is important here due to its memory visibility effects.
Presence of final
guarantees that other threads would see values in the map after constructor finished without any external synchronization. Without final
it cannot be guaranteed in all cases, and you would need to use safe publication idioms when making newly constructed object available to other threads, namely (from Java Concurrency in Practice):
- Initializing an object reference from a static initializer;
- Storing a reference to it into a volatile field or AtomicReference;
- Storing a reference to it into a final field of a properly constructed object; or
- Storing a reference to it into a field that is properly guarded by a lock.
Yes it is. There is no way to modify the reference aMap
itself, or add to the map after the constructor (barring reflection).
If you expose aMap
it will not be, because two threads could then modify the map at the same time.
You could improve your class by making aMap
unmodifiable via Collections.unmodifiableCollection or Collections.unmodifiableMap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With