在 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/