8
votes

Enums are considered best way for singletons and one of reasons for this is that it implicitly inherits Serializable.

But how enums prevents de-serialization problem of singletons?

2
Enum is a singleton but what are the problems of deserialization of singletons ? - clinton
@clinton: if you make a singleton serializable, and don't care about how it's deserialized, you and up with a new instance of your singleton each time it's deserialized, which breaks its singletonness. - JB Nizet
@JBNizet thanks for the info. I had not looked up that issue regarding singletons before now. Or it may not have struck me as important. - clinton

2 Answers

7
votes

The serialization mechanism handles them in a special, specific way. But traditional singletons can be deserialized fine by defining a readResolve() method that returns the unique instance. See http://www.oodesign.com/singleton-pattern.html for an example.

1
votes

Serialization as an argument for using enum for singleton is nonsense.

If the enum singleton is stateful, the state is lost during serialization/deserialization.

If the singleton is stateless, who cares about its identity?