1、 意圖
多線程中,創建線程安全的單件模式。
2、 問題
多線程中,Singleton模式並不總是正常工作的。
3、 解決方案
在檢查到null或實例未創建之後進行“同步”,然後再檢查一次,確保實例尚未創建
4、 效果
Singleton模式的變體,優化掉不必要的鎖定,這種同步檢查最多進行一次,因此不會成爲瓶頸。
5、 實現
// .Net中通過MemoryBarrier 實現
public class MySingleton {
private static object myLock = new object();
private static MySingleton mySingleton = null;
private static bool ready = false;
private MySingleton() {
}
public static MySingleton GetInstance() {
if (!ready) { // 1st check
lock (myLock) {
if (!ready) { // 2nd (double) check
mySingleton = new MySingleton();
System.Threading.Thread.MemoryBarrier(); // fence
ready = true;
}
}
}
return mySingleton;
}
}
// 使用C#關鍵字volatile實現,會降低效率
public class MySingleton {
private static object myLock = new object();
private static volatile MySingleton mySingleton = null;
private MySingleton() {
}
public static MySingleton GetInstance() {
if (mySingleton == null) { // check
lock (myLock) {
if (mySingleton == null) { // double check, volatile ensures that the value is re-read
mySingleton = new MySingleton();
}
}
}
return mySingleton;
}
}
// .net 4.0中可以使用Lazy<T>實現
public class MySingleton
{
private static readonly Lazy<MySingleton> mySingleton =
new Lazy<MySingleton>(() => new MySingleton());
private MySingleton()
{ }
public static MySingleton GetInstance()
{
return mySingleton.Value;
}
}