lundi 8 octobre 2018

Singleton pattern in multi-threading may have duplication code

I saw there is a tutorial online for Singleton, in order to implement multi-threading and ensure the instance only be instantiate once. The tutorial has code below, but in the code, then there is duplication code, as they want to make sure the instance is not null.

if(instance == null){} 

However, this condition check show up twice, is this duplication ?

    public class Singleton {
        private static Singleton instance;


        private Singleton(){
            //Here runs a lot code, that's why we don't want to instantiate here
        }

        // Using synchronized to ensure Singleton (only instantiate once) when 
        //implement multi threading.
        public static Singleton getInstance(){
            if(instance == null){
                synchronized(Singleton.class){
                    if(instance == null){
                        instance = new Singleton();
                    }    
                }
            } 
            return instance;
        }

    }

Aucun commentaire:

Enregistrer un commentaire