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被实例化,虽然它从未被要求过.
但是拥有私有静态方法/字段是可以的,因此其他人不会偶然触发类初始化.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。