Java

How to protect Singleton design pattern from multiple instantiations?

How to protect Singleton design pattern from multiple instantiations?

Singleton design pattern is one of the popular design pattern, which ensures that only one instance of a class can be created and provides a global point of access to that instance. But there are many ways through which hackers can break this.

Following are the ways by which multiple instances can be created for Singleton class and preventive measures to protect the code:

1.     Reflection

Reflection can be caused to destroy singleton property of singleton class, as shown in following example:

 

 

The above code ends up creating two instances of the Singleton class which breaks the rule.

 

Output

 

Solution

To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.

 

 

JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also.

2.     Cloning

Cloning is the concept to create copy of object, it comes under prototype design pattern and it can break Singleton pattern by creating of copy of singleton instance.

 

 

Output

 

Solution

Override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.

 

Output

3.     Serialization

Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then when de-serializing that object it will create a new instance and break the singleton pattern.

 

Output

Solution

Implement method readResolve() method of Serializable interface and return instance of Singleton class.

 

 

Output

These were the ways to protect Singleton class from multiple instantiations.

Happy Learning!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.