java – 免费的懒惰初始化

前端之家收集整理的这篇文章主要介绍了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年了.信息是否仍然相关?)

最佳答案
这意味着,如果一个类没有其他方法或字段,那么你只能为单例访问它,所以只在需要时创建单例.否则,例如

  1. class Foo
  2. {
  3. public static final Foo foo = new Foo();
  4. public static int x() { return 0; }
  5. }
  6. class AnotherClass
  7. {
  8. void test()
  9. {
  10. print(Foo.x());
  11. }
  12. }

在这里,foo被实例化,虽然它从未被要求过.

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

猜你在找的Java相关文章