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)