加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 免费的懒惰初始化

发布时间:2020-12-14 06:08:06 所属栏目:Java 来源:网络整理
导读:在一个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 metho

在一个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被实例化,虽然它从未被要求过.

但是拥有私有静态方法/字段是可以的,因此其他人不会偶然触发类初始化.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读