Break singleton pattern


What are the different ways we can break a singleton pattern in Java?

  • Use reflection to access the private constructor and instantiate the class as many times as you want.(can prevent using early initialization)
  • Serialization. If you do not implement readResolve then reading a singleton with
          ObjectInputStream.readObject() will return a new instance of this singleton.
  • Clone() :Preferred way is not to implement Cloneable interface. 

double locked Singleton

How to write double locked Singleton class in Java ?

we can check double locked in java singleton class as below code

public class SingletonInstanceDemo {
    private static volatile SingletonInstanceDemo instance = null;
    // private constructor
    private SingletonInstanceDemo() {
    }
    public static SingletonInstanceDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonInstanceDemo.class) {
                // Double check
                if (instance == null) {
                    instance = new SingletonInstanceDemo ();
                }
            }
        }
        return instance;
    }
}