Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums, Singletons and Deserialization

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?

like image 283
a Learner Avatar asked Nov 04 '12 15:11

a Learner


People also ask

Are enums singletons?

Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.

Is enum Singleton lazy?

In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code. So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.

Why enums are better than constants?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

Why is enum thread safe?

This technique is absolutely thread-safe. An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.


2 Answers

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.

like image 99
JB Nizet Avatar answered Oct 12 '22 17:10

JB Nizet


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?

like image 33
irreputable Avatar answered Oct 12 '22 17:10

irreputable