急切初始化singleton vs lazy初始化单例

时间:2016-03-22 19:16:37

标签: java design-patterns singleton

在思考单例设计模式的同时,我陷入了渴望初始化单例和静态块初始化单例模式之间。 让我们说急切初始化单例类代码是 -

public class EagerInitSingleton {

    private static final EagerInitSingleton instance = new EagerInitSingleton();

    //private constructor
    private EagerInitSingleton(){}

    public static EagerInitSingleton getInstance(){
        return instance;
    }
}

和静态块单例类代码如下 -

public class StaticBlockSingleton {

    private static StaticBlockSingleton instance;

    private StaticBlockSingleton(){}

    //static block initialization for exception handling
    static{
        try{
            instance = new StaticBlockSingleton();
        }catch(Exception e){
            throw new RuntimeException("Exception occured in singleton instance");
        }
    }

    public static StaticBlockSingleton getInstance(){
        return instance;
    }
}

请不要谈论懒惰的初始化和线索安全。 我想弄清楚静态块单例中的两个静态块如何在这里产生差异。

1 个答案:

答案 0 :(得分:1)

没有区别。

private static final EagerInitSingleton instance = new EagerInitSingleton();

相当于

private static final EagerInitSingleton instance;

static {
    instance = new EagerInitSingleton();
}