Why Enum Singleton Are Improve Inwards Java

Advertisement

Masukkan script iklan 970x90px

Why Enum Singleton Are Improve Inwards Java

Rabu, 03 Maret 2021

Enum Singletons are novel means to implement Singleton pattern inward Java past times using Enum amongst merely i 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 afterwards introduction of Enum every bit keyword together with feature. This article is somewhat related to my before postal service on Singleton, 10 interview questions on Singleton pattern inward Java where nosotros bring discussed mutual questions asked on interviews nigh Singleton pattern together with 10 Java enum examples, where nosotros bring seen how versatile enum tin be. This postal service is nigh why should nosotros purpose Enum every bit Singleton inward Java, What do goodness it offers compared to conventional singleton methods etc.

Java Enum together with Singleton Pattern


1) Enum Singletons are tardily to write
This is past times far biggest advantage, if you lot bring been writing Singletons prior ot Java five than you lot know that fifty-fifty amongst double checked locking you lot tin bring to a greater extent than than i instances. though that number is fixed amongst Java retention model improvement together with gurantee provided past times volatile variables from Java five onwards but it yet tricky to write for many beginners. compared to double checked locking amongst synchronization Enum singletons are cake walk. If you lot don't believe than merely compare below code for conventional singleton amongst double checked locking together with Enum Singletons:


Singleton using Enum inward Java
This is the means nosotros to a greater extent than oft than non declare Enum Singleton , it may incorporate instace variable together with illustration method but for sake of simplicity I haven’t used any, merely beware that if you lot are using whatever illustration method than you lot demand to ensure thread-safety of that method if at all it touching on the state of object. By default creation of Enum illustration is thread condom but whatever other method on Enum is programmers responsibility.

/**
* Singleton pattern illustration using Java Enumj
*/
public enum EasySingleton{
    INSTANCE;
}

You tin acess it past times EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.

Singleton illustration amongst double checked locking
Below code is an illustration of double checked locking inward Singleton pattern, hither getInstance() method checks 2 times to encounter whether INSTANCE is zilch or non together with that’s why it’s called double checked locking pattern, recall that double checked locking is broker before Java five but amongst the guranteed of volatile variable inward Java 5 retention model, it should hold upward perfectly.

/**
* Singleton pattern illustration amongst 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;
     
}
}

You tin telephone telephone DoubleCheckedLockingSingleton.getInstance() to instruct 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 you lot tin bring that inward i describe of piece of work because creation of Enum illustration is thread-safe together with guranteed past times JVM.

People may struggle that at that topographic point are meliorate means to write Singleton instead of Double checked locking approach but every approach has at that topographic point ain advantages together with disadvantages similar I mostly prefer static plain Singleton intialized during classloading every bit shwon inward below example, but hold upward out along inward hear that is non a lazy loaded Singleton:

Singleton pattern amongst static manufacturing works life method
This is i of my favorite method to impelemnt Singleton pattern inward Java, Since Singleton illustration is static together with final variable it initialized when shape is starting fourth dimension loaded into memeory together with hence creation of illustration is inherently thread-safe.

/**
* Singleton pattern illustration amongst static manufacturing works life method
*/


public class Singleton{
    //initailzed during shape loading
    private static final Singleton INSTANCE = new Singleton();
 
    //to forbid creating to a greater extent than or less other illustration of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

You tin telephone telephone Singleton.getSingleton() to instruct access of this class.


2) Enum Singletons handled Serialization past times themselves
Another work amongst conventional Singletons are that i time you lot implement serializable interface they are no longer stay Singleton because readObject() method e'er render a novel illustration merely similar constructor inward Java. you lot tin avoid that past times using readResolve() method together with discarding newly created illustration past times replacing amongst Singeton every bit shwon inward below illustration :

    //readResolve to forbid to a greater extent than or less other illustration of Singleton
   
private Object readResolve(){
       
return INSTANCE;
   
}

This tin instruct fifty-fifty to a greater extent than complex if your Singleton Class keep state, every bit you lot demand to brand them transient, but witn Enum Singleton, Serialization is guarnateed past times JVM.

3) Creation of Enum illustration is thread-safe
As stated inward indicate 1 since creatino of Enum illustration is thread-safe past times default you lot don't demand to worry nigh double checked locking.

In summary, given the Serialzation together with thraead-safety guaranteed together with amongst span of describe of piece of work of code enum Singleton pattern is best means to do Singleton inward Java five world. you lot tin yet purpose other pop methods if you lot experience together with hence but I yet bring to detect a convincing argue non to purpose Enum every bit Singleton, allow me know if you lot got any.

Further Learning
Complete Java Masterclass
Why multiple inheritance is non supported inward Java