重学设计模式 - Double-Checked Locking模式
2012-05-20 11:48
141 查看
1、
意图
多线程中,创建线程安全的单件模式。
2、
问题
多线程中,Singleton模式并不总是正常工作的。
3、
解决方案
在检查到null或实例未创建之后进行“同步”,然后再检查一次,确保实例尚未创建
4、
效果
Singleton模式的变体,优化掉不必要的锁定,这种同步检查最多进行一次,因此不会成为瓶颈。
5、
实现
意图
多线程中,创建线程安全的单件模式。
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; } }
相关文章推荐
- 重学设计模式 - Composite(组合)模式 - 结构型
- 演义群侠传(十)【重学设计模式】
- java设计模式进阶_double-checked-locking
- java设计模式之单列模式(懒汉,恶汉,double-check- lock)
- (原创)重学设计模式,总结C#细节 一 简单工厂模式
- 重学设计模式 - Abstract Factory模式
- 重学设计模式 - Factory Method模式
- 重学设计模式 - Builder模式
- 重学java23种设计模式(3)建造者模式
- Java设计模式之单例模式 double---checked----locking双重检查锁定
- (设计模式)Singleton和Double-Checked Locking模式
- 重学设计模式(一) -- 工厂模式
- 重学设计模式 - Chain of Responsibility(责任链)模式 - 行为型
- 重学设计模式 - Decorator模式
- 重学设计模式 - Object Pool模式
- GoF著作中未提到的设计模式(4):Double Dispatch
- (原创)重学设计模式,总结C#细节 一 简单工厂模式
- 重学设计模式 - Template Method模式
- GoF著作中未提到的设计模式(4):Double Dispatch
- GoF著作中未提到的设计模式之四:Double Dispatch