Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

singleton

What are the different ways we can break a singleton pattern in Java. I know one way i.e. if we do not synchronize the method in singleton , then we can create more than an instance of the class. So synchronization is applied. Is there a way to break singleton java class.

public class Singleton {
    private static Singleton singleInstance;

    private Singleton() {
    }

    public static Singleton getSingleInstance() {
        if (singleInstance == null) {
            synchronized (Singleton.class) {
                if (singleInstance == null) {
                    singleInstance = new Singleton();
                }
            }
        }
        return singleInstance;
    }
}
like image 285
Harsha_2012 Avatar asked Dec 06 '13 10:12

Harsha_2012


1 Answers

One way is Serialization. If you do not implement readResolve then reading a singleton with ObjectInputStream.readObject() will return a new instance of this singleton.

like image 121
Evgeniy Dorofeev Avatar answered Nov 15 '22 21:11

Evgeniy Dorofeev