Either you want to keep things simple with an enum
public enum MySingleton {
INSTANCE
}
Or you have a good reason to make it more complicated
public class MySingleton {
private MySingleton() { }
private static MySingleton instance = null;
public synchronized static MySingleton getInstance() {
if (instance == null)
instance = new MySingleton();
return instance;
}
}
Either way, using volatile doesn't help.
IMHO, There isn't a good Singleton pattern where you would use volatile
so if it is needed, the code need fixing or simplifying.
AFAIK the only case where you would use volatile is for double-checked locking
public class MySingleton {
private MySingleton() { }
private static volatile MySingleton instance = null;
public static MySingleton getInstance() {
if (instance == null)
synchronzied(MySingleton.class) {
if (instance == null)
instance = new MySingleton();
}
return instance;
}
}
For comparison, the enum
example above does much the sample thing.
http://javarevisited.blogspot.co.uk/2011/06/volatile-keyword-java-example-tutorial.html
http://www.ibm.com/developerworks/java/library/j-dcl/index.html