I understand from the page "Double-Checked Locking is Broken" Declaration
that the idiom does not work in the general case. Just wonder if the
following code will work in the specific case of a static singleton object
of a class:
public class Singleton {
private static Singleton instance;
// other non-static member fields ...
private Singleton() {
// do whatever necessary for the non-static member fields...
}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Specifically, when the caller gets the object back from
Singleton.getInstance(), is the Singleton object guaranteed to be fully
initialized for the non-static member fields via the constructor in the
current Java Memory Model in a platform independent way ? (i.e Does it work
in the presence of either optimizing compilers or shared memory
multiprocessors ?)
Thanks,
Hanson
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:38 EDT