Why Enum Singleton Are Amend Inward Java

Enum Singletons are novel means to implement Singleton pattern inward Java past times using Enum alongside merely 1 instance. Though Singleton pattern inward Java exists from long fourth dimension Enum Singletons are relatively novel concept as well as inward exercise from Java v onwards later introduction of Enum every bit keyword as well as 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 virtually Singleton pattern as well as 10 Java enum examples, where nosotros convey seen how versatile enum tin dismiss be. This post service is virtually why should nosotros role Enum every bit Singleton inward Java, What do goodness it offers compared to conventional singleton methods etc.

Java Enum as well as Singleton Pattern


1) Enum Singletons are slow to write
This is past times far biggest advantage, if you lot convey been writing Singletons prior ot Java v than you lot know that fifty-fifty alongside double checked locking you lot tin dismiss convey to a greater extent than than 1 instances. though that number is fixed alongside Java retentiveness model improvement as well as gurantee provided past times volatile variables from Java v onwards but it nonetheless tricky to write for many beginners. compared to double checked locking alongside synchronization Enum singletons are cake walk. If you lot don't believe than merely compare below code for conventional singleton alongside double checked locking as well as 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 as well as instance method but for sake of simplicity I haven’t used any, merely beware that if you lot are using whatsoever instance method than you lot demand to ensure thread-safety of that method if at all it comport on the field of object. By default creation of Enum instance is thread prophylactic but whatsoever other method on Enum is programmers responsibility.

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

You tin dismiss 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 nil or non as well as that’s why it’s called double checked locking pattern, recall that double checked locking is broker before Java v but alongside the guranteed of volatile variable inward Java 5 retentiveness model, it should operate perfectly.

/**
* 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;
     
}
}

You tin dismiss telephone telephone DoubleCheckedLockingSingleton.getInstance() to larn 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 dismiss convey that inward 1 occupation because creation of Enum instance is thread-safe as well as guranteed past times JVM.

People may combat that at that spot are amend means to write Singleton instead of Double checked locking approach but every approach has at that spot ain advantages as well as disadvantages similar I mostly prefer static plain Singleton intialized during classloading every bit shwon inward below example, but continue 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 instance is static as well as final variable it initialized when bird is kickoff loaded into memeory then creation of instance is inherently thread-safe.

/**
* Singleton pattern instance alongside static mill method
*/


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

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

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


2) Enum Singletons handled Serialization past times themselves
Another work alongside conventional Singletons are that in 1 trial you lot implement serializable interface they are no longer stay Singleton because readObject() method ever render a novel instance merely similar constructor inward Java. you lot tin dismiss avoid that past times using readResolve() method as well as discarding newly created instance past times replacing alongside Singeton every bit shwon inward below instance :

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

This tin dismiss expire 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 instance is thread-safe
As stated inward betoken 1 since creatino of Enum instance is thread-safe past times default you lot don't demand to worry virtually double checked locking.

In summary, given the Serialzation as well as thraead-safety guaranteed as well as alongside twosome of occupation of code enum Singleton pattern is best means to do Singleton inward Java v world. you lot tin dismiss nonetheless role other pop methods if you lot experience then but I nonetheless convey to respect a convincing argue non to role Enum every bit Singleton, permit me know if you lot got any.

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

Belum ada Komentar untuk "Why Enum Singleton Are Amend Inward Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel