Ensures at most one instance of a particular class is ever created in your application.
Project Configuration: Class that reads your project configuration should be made Singleton by reads once and holds on application Cache and global access to all classes in application.
Application Log: Logger must be initialized once and used everywhere in application.
Analytics and Reporting: If you are using some kind of data analysis tool like Google Analytics, you will notice that they are designed to be singleton. It initializes once and being used everywhere for each user action.
Singleton and Thread Safety
Two instances of Singleton class will be created if the getInstance() called simultaneously by two threads. By making getInstance() method synchronized we will ensure that no two threads can be entered into getInstance() method at the same time.
Singleton and Early Initialization
Using early initialization we will initialize upfront before your class is being loaded. This way you don’t need to check for synchronization as it is initialized before being used ever.
Singleton and Object Cloning
Cloning is used to create a copy of object at any instance original object by implementing java.lang.Cloneable interface and override clone() method from Object class.
To prevent cloning on singleton object, explicitly throw CloneNotSupportedException exception in clone() method.
Singleton and Serialization
Java Serialization allows converting the state of an object into stream of bytes to store or transfer. Deserialization used to convert byte stream into. If a singleton class desterilized, it will end up creating duplicate objects.
To resolve this issue, we need to include readResolve() method in our class which will be invoked before the object is deserialized. We will return INTANCE by call getInstance() method inside readResolve() which will ensure single instance of Singleton class is exist application.