Can Java write a reference to an object before it is created by any method?
When using the double checked locking pattern (example and explanation taken from "Concurrency in Practice" there was a known bug):
@NotThreadSafe
public class DoubleCheckedLocking {
private static Resource resource;
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}
Some stream may display the initialized value of the "resource" variable, while the object itself is still under development.
This begs the question: is there still a problem if we build the resource object in some method? I.e
resource = createResource();
Can some thread evaluate the resource! = Null as true while the resource object is still in the process of being created in the createResource () method?
source to share
Yes, some stream can, or rather, it can. The code you posted is working correctly these days. Only with the earlier memory model (before Java 1.5) the DCL picture was wrong.
Also DCL is deprecated these days as the best way to create a lazy load singleton is with the singleton enum pattern.
source to share
To answer your question, in the example you provided, the behavior will not change if you use a method or call new
directly. What affects the behavior of threads is a memory barrier of some kind. Dispatching the method is not enough.
However, double check locking works with Java 5, although you need to use the keyword volatile
on the instance. (To provide a memory barrier, as is the case.)
source to share