Make the Singleton perfect
What is the purpose of Singleton?
The purpose of the Singleton class is to control object creation, limiting the number of objects to only one. The singleton allows only one entry point to create the new instance of the class.
Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons are often useful where you have to control the resources, such as database connections or sockets.
It seems to be a simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic among developers. Here, you are going to discuss how to create a Singleton class that fulfills its purpose :
Restrict the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
Let’s create Singleton class in java and test it in different conditions.
Now, above Singleton class is thread safe. Making Singleton thread safe is especially required in multi-threaded application environment like in Android Applications
How to Make Singleton safe from Serialization
Sometimes in distributed systems, you need to implement Serializable interface in Singleton class. By doing that you can store its state in the file system and retrieve it at later point of time.
Let’s test singleton class whether it maintains single instance after serializable and deserializable operations?
it will also create multiple instance in this case.
hat is clearly violates singleton principle. The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class.
To prevent creation of another instance you have to provide the implementation of readResolve() method. readResolve() replaces the object read from the stream. This ensures that nobody can create another instance by serializing and deserializing the singleton.
Salutation
Conclusion:
At end of the article, you can make your class a Singleton class that is thread, reflection and serialization safe. This Singleton is still not the perfect Singleton. You can violate the Singleton principle by creating more than one instance of the Singleton class by using cloning or using multiple class loaders. But for the most of the applications, above implementation of Singleton will work perfectly.
