mardi 19 février 2019

Why we need double check lock while designing singleton pattern in Java?

Why we need to check null before and after the lock acquition ? Once , we acquired the lock , no thread can own the lock then why not null check is required before the synchronization block?

public class DclSingleton {
    private static volatile DclSingleton instance;
    public static DclSingleton getInstance() {
        **if (instance == null) {**
            synchronized (DclSingleton .class) {
                **if (instance == null) {**
                    instance = new DclSingleton();
                }
            }
        }
        return instance;
    }

    // private constructor and other methods...
}

Aucun commentaire:

Enregistrer un commentaire