Also, how many ways we can break singleton class in Java?
There are mainly 3 concepts which can break singleton property of a class. Let's discuss them one by one. After running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.
Furthermore, how can you stop clone in a singleton Java class? You can avoid cloning by giving already created object by clone method. You need to override the clone() method only if your singleton class implements Cloneable interface or a class which implements Cloneable interface.
Additionally, what are the ways to break Singleton?
Deserialization. In serialization, we can save the object of a byte stream into a file or send over a network. Suppose if you serialize the Singleton class, and then again de-serialize that object, it will create a new instance, hence deserialization will break the Singleton pattern.
How do you serialize a singleton object in Java?
Conclusion: Singleton class can also be serialized by keeping readResolve() method in the Singleton class. This may be a familiar solution but just in case for reference. So if we execute above code we will get following behaviour: "it has created two objects and one static reference for INSTANCE.