考虑您有以下代码:
1.为什么我们使用双重检查锁,为什么单锁不够好,请提供详细的例子
2.这种实施的主要缺点是什么?我该如何证明呢?
感谢。
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;
}
}
}
答案 0 :(得分:8)
我认为单例类的最佳实现是由Jon Skeet
提供的。
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
答案 1 :(得分:2)
if(s_Instance == null)
检查,就会获得锁定每个时间有人访问单身人士。但实际上只需要在实例创建期间锁定。所以第一个if(s_Instance == null)
可以防止不必要的锁定。第二个if(s_Instance == null)
需要存在,因为最初两个线程可能已将第一个if(s_Instance == null)
评估为true
,然后两个线程将在锁内相互实现s_Instance
。 您可以使用静态构造函数来改进它:
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;
}
}
}