简体   繁体   English

Java-对象创建和可见性

[英]Java - object creation and visibility

Given the following code: 给出以下代码:

class MyObj{
   AtomicLong counter;

   public MyObj(){
       count = new AtomicLong();
   }
}

MyObj obj = new MyObj();
// start a few threads that referencey obj and access counter

I would like to know if there is a potential scenario here, that the created threads will see the state of MyObj as incomplete, due to compiler reodering/inlining? 我想知道这里是否存在潜在的情况,由于编译器重新编排/内联,创建的线程将看到My​​Obj的状态为不完整? For instance, they might see counter = null , or counter partially created, as it is not a final field? 例如,他们可能会看到counter = null或部分创建的计数器,因为它不是最终字段?

There are two situations: 有两种情况:

  • if you start the threads after MyObj obj = new MyObj() , there is a happens-before relationship that guarantees that the threads will all see the correctly constructed object 如果您 MyObj obj = new MyObj() 之后启动线程,则存在一个before-before关系,该关系确保线程将全部看到正确构造的对象
  • if you start the threads before , there is no guarantee of anything (they could observe obj == null or obj != null && obj.counter == null or obj != null && obj.counter != null ). 如果您之前启动线程,则无法保证(它们可以观察到obj == nullobj != null && obj.counter == nullobj != null && obj.counter != null )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM