Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as
public class Singleton {
private static Singleton re
Why can't you do just
public class SingletonSandBox {
private static SingletonSandBox instance = new SingletonSandBox();
private SingletonSandBox(){
}
public static SingletonSandBox getInstance(){
return instance;
}
}
and test
public static void main(String[] args) {
SingletonSandBox sss1 = SingletonSandBox.getInstance();
SingletonSandBox sss2 = SingletonSandBox.getInstance();
System.out.println(sss1 == sss2);
}
As I know this is thread-safe and shorter than using static block. Again static field declaration is read earlier comparing to static block by the runtime.