You can also create thread safe Singleton in Java by creating Singleton instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created. Here is example of creating thread safe singleton in Java using static factory method. Only disadvantage of this implementing Singleton patter using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method.
public class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){ }
public static Singleton getInstance(){
return INSTANCE;
}
public void show(){
System.out.println("Singleon using static initialization in Java");
}
}
//Here is how to access this Singleton class
Singleton.getInstance().show();
here we are not creating Singleton instance inside getInstance() method instead it will be created by ClassLoader. Also private constructor makes impossible to create another instance , except one case. You can still access private constructor by reflection and calling setAccessible(true). By the way You can still prevent creating another instance of Singleton by this way by throwing Exception from constructor.