Thursday, September 25, 2014

Double check singleton design pattern

public class MySingleton {
    private static object myLock = new object();
    private static volatile MySingleton mySingleton = null; // 'volatile' is unnecessary in .NET 2.0 and later
 
    private MySingleton() {
    }
 
    public static MySingleton GetInstance() {
        if (mySingleton == null) { // 1st check
            lock (myLock) {
                if (mySingleton == null) { // 2nd (double) check
                    mySingleton = new MySingleton();
                    
                }
            }
        }

        return mySingleton;
    }
}

No comments:

Post a Comment