【问题标题】:singleton design pattern with thread safe具有线程安全的单例设计模式
【发布时间】:2014-06-13 01:31:57
【问题描述】:

我读到同步新实例创建的原因是两个线程可以同时访问getInstance并发现_instance为null并创建两个Singleton类实例。所以为了消除我们同步它。但是再次引入双重检查锁定方法如何再次检查 Synchronized 块内的实例是否为空。这有必要吗?一旦一个代码块被同步,它就已经是线程安全的了?

public class Singleton {
        private static Singleton _instance = null;

        private Singleton() {   }

        public static Singleton getInstance() {
                if (_instance == null) {
                      synchronized (Singleton.class) {
                          _instance = new Singleton(); // why need to again check null
                      }
                }
                return _instance;
        }
} 

【问题讨论】:

标签: singleton


【解决方案1】:

synchronized 块将按顺序执行(即一次一个线程),但这还不够,因为对 _instance = new Singleton() 的第二次调用可能会覆盖第一次。

如果一个上下文切换在第一个线程计算 _instance == null 表达式后立即发生,并且在另一个线程计算 _instance == null 表达式之前没有其他上下文切换发生,这是一个合理的场景。

因此,一旦进入synchronized 块,当前线程必须确保_instance 仍然是null,然后再将其设置为new Singleton()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2020-02-22
    • 2013-07-27
    • 2020-07-17
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多