Singleton design pattern with double-check lock

邮差的信 提交于 2019-12-08 01:21:05

问题


Consider you have the following code:
1. Why do we use double check lock, why single lock is not good enough, please provide detailed example.
2. What are the main drawbacks with this implementation? and how should I prove it?
Thanks.

 public sealed class SomeSingleton5  
{  
    private static SomeSingleton5 s_Instance = null;
    private static object s_LockObj = new Object();

    private SomeSingleton5() { }

    public static SomeSingleton5 Instance
    {
        get
        {
            if (s_Instance == null)
            {
                lock (s_LockObj)
                {
                    if (s_Instance == null)
                    {
                        s_Instance = new SomeSingleton5();
                    }
                }
            }

            return s_Instance;
        }
    }
}

回答1:


I think the best implementation of singleton class is provided by Jon Skeet.

public sealed class Singleton
{
  private static readonly Singleton instance = new Singleton();
  public static Singleton Instance { get { return instance; } }
  static Singleton() {}
  private Singleton() {}
}

Singleton by Jon Skeet Clarification




回答2:


  1. Aquiring a lock is expensive. Without the first if(s_Instance == null) check, a lock would be aquired each time someone accesses the singleton. But a lock actually only needs to be there during instance creation. So the first if(s_Instance == null) prevents the unnecessary locking. The second if(s_Instance == null) needs to be there because initially two threads might have evaluated the first if(s_Instance == null) as true and the two threads would thereafter instanciate s_Instance after each other inside the lock.
  2. I don't see any real drawbacks in your implementation but with the alternative (static constructor, see below) we have a solution that is simpler and involves less code. So it is more maintainable and less errorprone. Also it doesn't require locking at all. As mentioned earlier, locking is expensive.

you can improve it by using a static constructor:

public sealed class SomeSingleton5  
{  
    // the compiler will generate a static constructor containing the following code 
    // and the CLR will call it (once) before SomeSingleton5 is first acccessed
    private static SomeSingleton5 s_Instance = new SomeSingleton5();

    private SomeSingleton5() { }

    public static SomeSingleton5 Instance
    {
        get
        {
            return s_Instance;
        }
    }
}


来源:https://stackoverflow.com/questions/11328186/singleton-design-pattern-with-double-check-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!