Avoid multiple instances of Singleton?

I believe that when a singleton object becomes serialized and then deserialized many times in a row, there are several instances of the created singleton.

How can you avoid such a situation?

+6
source share
2 answers

Usually, when you create a Singleton, you will see that there is only one instance. you can do it like this:

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 in private ensures that no one except this class can instantiate a Singleton.

You only need to call Singleton with getInstance, and Singleton do all the work on its side.

+2
source

Joshua Bloch talks about using enumeration as a singlet to avoid this particular problem in Effective Java . Check out this article: Why Enumerations Are the Best Singletones , or Read It Directly from a Flea.

+4
source

Source: https://habr.com/ru/post/971117/


All Articles