top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why Enum Singleton are better in Java Explain with example?

+1 vote
402 views
Why Enum Singleton are better in Java Explain with example?
posted Apr 30, 2015 by Roshni

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The following some reason Enum Singleton are Better in Java:

1) Enum Singletons are easy to write

2) Enum Singletons handled Serialization by themselves

Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as Shown below example :

//readResolve to prevent another instance of Singleton
private Object readResolve(){
    return INSTANCE;
}

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but witn Enum Singleton, Serialization is guarnateed by JVM.

3) Creation of Enum instance is thread-safe

creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking.

answer May 5, 2015 by Karthick.c
...