I believe when a singleton object gets serialized and is then deserialized upon a plethora of times in series, there are multiple instances of singletons created.
How can you avoid such a situation?
Prevent Singleton Pattern From Cloning To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception, as shown in the below code.
The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
The object cloning is a way to create exact copy of an object. So if somebody will clone our singleton instance, it will create another copy of the Singleton instance which violates principle of Singleton Design Pattern.
Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.
Normally, when you are creating a Singleton, you make sure that there is only one instance of it. you could do it that way:
public static class Singleton{
private final static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null)
instance = new Singleton();
return instance;
}
}
Putting the constructor to private
makes sure that no one except this class can create an instance of Singleton.
You only need to call the Singleton with getInstance and the Singleton do all the work on its side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With