double check locking in singleton pattern

前端 未结 6 1187
死守一世寂寞
死守一世寂寞 2021-01-17 08:14

it may be basic question

to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locki

6条回答
  •  粉色の甜心
    2021-01-17 08:33

    Multithreaded Singleton : The best approach to use double check locking

    public sealed class Singleton
    {
       private static volatile Singleton _instance;
       private static readonly object InstanceLoker= new Object();
    
       private Singleton() {}
    
       public static Singleton Instance
       {
          get 
          {
             if (_instance == null) 
             {
                lock (InstanceLoker) 
                {
                   if (_instance == null) 
                      _instance = new Singleton();
                }
             }
    
             return _instance;
          }
       }
    }
    

提交回复
热议问题