Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is singleton pattern and double checked locking ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.50k
    Comment on it

    Singleton pattern is basically used to maintain only a single object of a class in the application. This uses private constructor and static method to return class instance like this :

    public class SingleTon {
        
        private static SingleTon singleTon;
        
        private SingleTon(){}
        
        public static SingleTon getInstance(){
            if (singleTon == null) {
                        singleTon = new SingleTon();
            }
            return singleTon;
        }
    }

     

    but you know that in some cases if more than two threads are using the same method at a time there might be more than one object so for this we should make it thread safe by using synchronized like this :

    public class SingleTon {
        
        private static SingleTon singleTon;
        
        private SingleTon(){}
        
        public static synchronized SingleTon getInstance(){
            
            if (singleTon == null) {
                        singleTon = new SingleTon();
            }
            return singleTon;
        }
    }

    Note : sometimes it is important to double checked locking on object because by using synchronization only one thread can access the same method other ll have to wait, so for double-checked locking, you can do this :
     

    public class SingleTon {
        
        private static SingleTon singleTon;
        
        private SingleTon(){}
        
        public static synchronized SingleTon getInstance(){
            
            if (singleTon == null) {
                synchronized (singleTon) {
                    if (singleTon == null) {
                        singleTon = new SingleTon();
                    }
                }
            }
            return singleTon;
        }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: