您的位置:首页 > 其它

重学设计模式 - Double-Checked Locking模式

2012-05-20 11:48 141 查看
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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: