java - 免费延迟初始化

标签 java jvm singleton lazy-initialization double-checked-locking

article 中在双重检查锁定习惯用法上,我发现了这句话:

One special case of lazy initialization that does work as expected without synchronization is the static singleton. When the initialized object is a static field of a class with no other methods or fields, the JVM effectively performs lazy initialization automatically.

为什么强调的部分很重要?如果有 其他方法或字段,为什么它不起作用?

(这篇文章已经超过 10 年了。这些信息是否仍然相关?)

最佳答案

意思可能是,如果一个类没有其他方法或字段,那么您只能为单例访问它,因此只有在需要时才创建单例。否则,例如

class Foo 
{
    public static final Foo foo = new Foo();

    public static int x() { return 0; }
}

class AnotherClass
{
    void test() 
    {
        print(Foo.x());
    }
}

这里,foo 被实例化了,尽管它从未被要求过。

但是有私有(private)静态方法/字段是可以的,这样其他人就不会意外触发类初始化。

关于java - 免费延迟初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14657275/

相关文章:

Java 在发生 OutOfMemoryError 错误之前清空缓存

java - 单例是有状态的吗?

java - 尝试从 Java 实例化 Scala 类时出现异常

java - 在激活菜单项时显示标签

java - 关于TLS 1.2和jdk版本的困惑

java - 长时间偶然的 Young 垃圾收集暂停

java - 在 Guice 中访问注入(inject)的依赖项

ios - 如何正确地将单例分配给 iOS 中的变量?

java - 阻止用户浏览互联网

java - 有没有更短的方法来编写这个 FXML 摘录?