【问题标题】:Singleton pattern in multi-threading may have duplication code多线程中的单例模式可能有重复代码
【发布时间】:2018-10-08 13:19:49
【问题描述】:

我看到网上有一个Singleton的教程,为了实现多线程并确保实例只被实例化一次。本教程下面有代码,但在代码中,则有重复代码,因为他们要确保实例不为空。

if(instance == null){} 

但是,这个条件检查出现了两次,这是重复吗?

    public class Singleton {
        private static Singleton instance;


        private Singleton(){
            //Here runs a lot code, that's why we don't want to instantiate here
        }

        // Using synchronized to ensure Singleton (only instantiate once) when 
        //implement multi threading.
        public static Singleton getInstance(){
            if(instance == null){
                synchronized(Singleton.class){
                    if(instance == null){
                        instance = new Singleton();
                    }    
                }
            } 
            return instance;
        }

    }

【问题讨论】:

  • 它被称为double checked locking 是有原因的。
  • 为确保没有多线程破坏单例模式,请在您的类中添加 object 并在检查 null 之前添加 lock
  • @nalka OP 没有询问对象锁定。他们在问为什么instance 会被检查两次。请不要添加无关信息,因为它只会混淆OP。
  • 事实检查了两次,但在这种特定情况下,有充分的理由检查两次。检查@bommelding 链接(它是java,但概念相同)或我的答案,我试图解释为什么需要第二个if

标签: c# design-patterns singleton code-duplication code-cleanup


【解决方案1】:

没有重复。再次检查它是因为在第一次检查if(instance == null) 和锁定synchronized(Singleton.class) 之间,另一个线程可以实例化它并破坏单例。检查第一个代码块和第二个代码块之间的差异。

    public static Singleton getInstance(){
        if(instance == null){
            // Another thread could instantiate in this moment.
            synchronized(Singleton.class){
                instance = new Singleton(); // If another thread did already instantiate it, this would be the second call to the constructor.
            }
        } 
        return instance;
    }

在锁定完成后再次检查可以防止这种竞争条件。

    public static Singleton getInstance(){
        if(instance == null){
            // Another thread could instantiate in this moment.
            synchronized(Singleton.class){
                // Now this code is thread safe
                if(instance == null){
                    // No other thread made a race condition before the first check and the locking. We can safely do the heavy work.
                    instance = new Singleton();
                }    
            }
        } 
        return instance;
    }

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多