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

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...