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?
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?
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.
Joshua Bloch talks about using an enum as a singleton to avoid this specific issue in Effective Java. Check out this article: Why Enums are Better Singletons -or- read it directly from Bloch here.