jeudi 3 octobre 2019

Question about logic used in thread safe design?

Below is the code snippet for thread safe design. Why are we checking for instance = null both before and inside the synchronized block? Isn't it sufficient to check for it outside?

// double locking is used to reduce the overhead of the synchronized method
public static ThreadSafeSingleton getInstanceDoubleLocking() {
    if (instance == null) {
        synchronized (ThreadSafeSingleton.class) {
            if (instance == null) {
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

Aucun commentaire:

Enregistrer un commentaire