mardi 30 juin 2020

Difference in Implementations of Thread Safe Singleton Design Patteren

What is the difference between thread-safe Singleton Design Pattern with Double Check Locking as in the below code.

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (this) {
                if(instance==null)
                    instance = new Singleton();
             }
        }
        return instance;
    }
}

And in below implementation other than Eager initialization.

public class Singleton {
    private static volatile Singleton instance = new Singleton();
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

Aucun commentaire:

Enregistrer un commentaire