非最终实例的线程安全惰性初始化

Thread-safe lazy initialization with non final instance

我看过这个答案here,展示了如何对静态最终单例进行线程安全的惰性初始化。

但是,如果 class 您延迟加载 不是 final,最好的解决方案是什么? (它有一些你想在创建后调用的方法)

将方法调用放在静态块中是否安全?

public class Something {

    private static class LazyHolder {
            public static final Something INSTANCE = new Something();
            static {
                    INSTANCE.setValue("foo");
            }
    }

    public static Something getInstance() {
            return LazyHolder.INSTANCE;
    }
}

这是 IODH(按需初始化方法)的惯用语。

But what is the best solution if the class you are lazy loading isn't final? (It has some methods you want to call after creating it)

你的"INSTANCE"是否是最终的并不重要。它将被延迟加载(当您第一次调用 getInstance 方法时)。
将 INSTACE 设置为 final 的目的是确保它始终指向一种对象,但您可以自由修改对象属性。