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

Viewed 37587

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;
    }
}
12 Answers

There are mainly 3 concepts that can break the singleton property of a class.

1. Reflection: Reflection can be caused to destroy the singleton property of the singleton class.

2. Serialization:- Serialization can also cause breakage of singleton property of singleton classes.

3. Cloning: Cloning is a concept to create duplicate objects. Using clone we can create a copy of an object.***
Related