Lazy Singleton比线程安全有什么优势

时间:2016-05-23 13:50:14

标签: java design-patterns

我们在学校有设计模式,并学习了单身(懒惰/非线程安全)的实现,如下所示:

package com.crunchify.tutorials;
public class CrunchifySingleton {

    private static CrunchifySingleton instance = null;

    protected CrunchifySingleton() {
    }

    // Lazy Initialization (If required then only)
    public static CrunchifySingleton getInstance() {
        if (instance == null) {
            // Thread Safe. Might be costly operation in some case
            synchronized (CrunchifySingleton.class) {
                if (instance == null) {
                    instance = new CrunchifySingleton();
                }
            }
        }
        return instance;
    }
}

现在我找到了这样的实现:

package com.crunchify.tutorials;

public class ThreadSafeSingleton {

    private static final Object instance = new Object();

    private ThreadSafeSingleton() {
    }

    // Runtime initialization
    // By defualt ThreadSafe
    public static Object getInstance() {
        return instance;
    }
}

现在我想知道第一个实现何时使用更有意义,因为根据http://crunchify.com/thread-safe-and-a-fast-singleton-implementation-in-java/,第二个是线程安全的,需要更少的行。

2 个答案:

答案 0 :(得分:0)

区别在于单例对象被实例化的时间。第二个片段在类实例化时仅实例化一次singleton对象。如果此过程不需要其他数据,则非常有用。请注意,如果发生实例化错误(在这种简单的情况下无关紧要:只是对象)单例类将根本不可用。

第一个代码段在请求时实例化单个对象。您可以修改该类以提供一些机制来存储任何初始化数据和/或捕获实例化错误。

答案 1 :(得分:0)

如何防止Singleton的多个实例由于任何原因。 Singleton的双重检查锁定是一种确保通过应用程序生命周期只创建一个Singleton类实例的方法。顾名思义,在双重检查锁定中,代码检查Singleton类的现有实例两次,有或没有锁定,以确保只创建一个单例实例。