Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MyS
The solution with enum won't work with Singletons managed by Spring, EJB, Guice or any other DI framework. It works only with enums, only because enum is treated specially by the serialization algorithm.
Firstly, singletons don't need serialization, because if you deserialized it, and then deserialized singleton != YourSingleton.getInstance(), it would mean that you have two instances of your singleton, which means that YourSingleton isn't singleton at all, which may lead to unpredictable bugs.
However sometimes you need to serialize non-singleton which contains a reference to singleton. The solution is easy:
class NonSingleton implements Serializable {
private transient YourSingleton singleton = YourSingleton.getInstance();
...
}
With Spring:
@Configurable
class NonSingleton implements Serializable {
@Autowired
private transient YourSingleton singleton;
...
}