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?
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.
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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With