In many cases implementing double-checked-locking in Java is not thread safe (the unsynchronized section of code can return partially initialized values). However, I'm using double-checked locking to check if a value is in a ConcurrentHashMap
, and if it isn't, then enter a synchronized block, create the object, and put
it in the map. Is this thread safe? That is, will the put
or get
method in ConcurrentHashMap
ever add or return partially constructed values (or do some other unexpected behavior)? Or are the get
and put
methods atomic, i.e. a successful put
guarantees that other threads will see the properly constructed object that was put in the map? Code is as follows:
public class MyClass {
private static ConcurrentHashMap<KeyObject, SingletonObject> myConcurrentMap = new Concurrent...
...
private static SingletonValue getFromConcurrentMap(KeyObject key) {
SingletonValue singleton = this.myConcurrentHashMap.get(key);
if (singleton == null) {
synchronized (this.myConcurrentHashMap) {
singleton = this.myConcurrentHashMap.get(domainRuleBase);
if (singleton == null) {
singleton = SingletonValue.buildNewInstance();
this.myConcurrentHashMap.put(key, singleton);
}
}
}
return singleton;
}
...
}