Why Enum Singleton Are Ameliorate Inward Java
Monday, August 27, 2018
Add Comment
Enum Singletons are novel agency to implement Singleton pattern inward Java past times using Enum alongside simply 1 instance. Though Singleton pattern inward Java exists from long fourth dimension Enum Singletons are relatively novel concept together with inward exercise from Java five onwards later introduction of Enum equally keyword together with feature. This article is somewhat related to my before post service on Singleton, 10 interview questions on Singleton pattern inward Java where nosotros convey discussed mutual questions asked on interviews near Singleton pattern together with 10 Java enum examples, where nosotros convey seen how versatile enum tin be. This post service is near why should nosotros run Enum equally Singleton inward Java, What do goodness it offers compared to conventional singleton methods etc.
Java Enum together with Singleton Pattern
Builder pattern pattern together with Decorator pattern pattern .
1) Enum Singletons are tardily to write
This is past times far biggest advantage, if y'all convey been writing Singletons prior ot Java five than y'all know that fifty-fifty alongside double checked locking y'all tin convey to a greater extent than than 1 instances. though that number is fixed alongside Java retentivity model improvement together with gurantee provided past times volatile variables from Java five onwards but it even together with hence tricky to write for many beginners. compared to double checked locking alongside synchronization Enum singletons are cake walk. If y'all don't believe than simply compare below code for conventional singleton alongside double checked locking together with Enum Singletons:
Singleton using Enum inward Java
This is the agency nosotros mostly declare Enum Singleton , it may incorporate instace variable together with lawsuit method but for sake of simplicity I haven’t used any, simply beware that if y'all are using whatsoever lawsuit method than y'all demand to ensure thread-safety of that method if at all it impact the dry reason of object. By default creation of Enum lawsuit is thread prophylactic but whatsoever other method on Enum is programmers responsibility.
/**
* Singleton pattern instance using Java Enumj
*/
* Singleton pattern instance using Java Enumj
*/
public enum EasySingleton{
INSTANCE;
}
INSTANCE;
}
You tin acess it past times EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.
Singleton instance alongside double checked locking
Below code is an instance of double checked locking inward Singleton pattern, hither getInstance() method checks 2 times to come across whether INSTANCE is zilch or non together with that’s why it’s called double checked locking pattern, retrieve that double checked locking is broker before Java five but alongside the guranteed of volatile variable inward Java 5 retentivity model, it should piece of work perfectly.
/**
* Singleton pattern instance alongside Double checked Locking
*/
* Singleton pattern instance alongside Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
private volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton(){}
public DoubleCheckedLockingSingleton getInstance(){
if(INSTANCE == null){
synchronized(DoubleCheckedLockingSingleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
private volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton(){}
public DoubleCheckedLockingSingleton getInstance(){
if(INSTANCE == null){
synchronized(DoubleCheckedLockingSingleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
You tin telephone telephone DoubleCheckedLockingSingleton.getInstance() to teach access of this Singleton class.
Now Just await at amount of code needed to do a lazy loaded thread-safe Singleton. With Enum Singleton pattern y'all tin convey that inward 1 trace of piece of work because creation of Enum lawsuit is thread-safe together with guranteed past times JVM.
People may fence that in that place are ameliorate agency to write Singleton instead of Double checked locking approach but every approach has in that place ain advantages together with disadvantages similar I mostly prefer static plain Singleton intialized during classloading equally shwon inward below example, but last past times along inward hear that is non a lazy loaded Singleton:
Singleton pattern alongside static mill method
This is 1 of my favorite method to impelemnt Singleton pattern inward Java, Since Singleton lawsuit is static together with final variable it initialized when course of report is starting fourth dimension loaded into memeory together with hence creation of lawsuit is inherently thread-safe.
/**
* Singleton pattern instance alongside static mill method
*/
public class Singleton{
//initailzed during course of report loading
private static final Singleton INSTANCE = new Singleton();
//to preclude creating roughly other lawsuit of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
* Singleton pattern instance alongside static mill method
*/
public class Singleton{
//initailzed during course of report loading
private static final Singleton INSTANCE = new Singleton();
//to preclude creating roughly other lawsuit of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
You tin telephone telephone Singleton.getSingleton() to teach access of this class.
2) Enum Singletons handled Serialization past times themselves
Another work alongside conventional Singletons are that 1 time y'all implement serializable interface they are no longer rest Singleton because readObject() method e'er render a novel lawsuit simply similar constructor inward Java. y'all tin avoid that past times using readResolve() method together with discarding newly created lawsuit past times replacing alongside Singeton equally shwon inward below instance :
//readResolve to preclude roughly other lawsuit of Singleton
private Object readResolve(){
return INSTANCE;
}
private Object readResolve(){
return INSTANCE;
}
This tin last past times fifty-fifty to a greater extent than complex if your Singleton Class hold state, equally y'all demand to brand them transient, but witn Enum Singleton, Serialization is guarnateed past times JVM.
3) Creation of Enum lawsuit is thread-safe
As stated inward shout out for 1 since creatino of Enum lawsuit is thread-safe past times default y'all don't demand to worry near double checked locking.
In summary, given the Serialzation together with thraead-safety guaranteed together with alongside duad of trace of piece of work of code enum Singleton pattern is best agency to do Singleton inward Java five world. y'all tin even together with hence run other pop methods if y'all experience together with hence but I even together with hence convey to discovery a convincing argue non to run Enum equally Singleton, allow me know if y'all got any.
Further Learning
Complete Java Masterclass
Why multiple inheritance is non supported inward Java
0 Response to "Why Enum Singleton Are Ameliorate Inward Java"
Post a Comment