[英]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? 我想知道这里是否存在潜在的情况,由于编译器重新编排/内联,创建的线程将看到MyObj的状态为不完整? For instance, they might see
counter = null
, or counter partially created, as it is not a final field? 例如,他们可能会看到
counter = null
或部分创建的计数器,因为它不是最终字段?
There are two situations: 有两种情况:
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关系,该关系确保线程将全部看到正确构造的对象 obj == null
or obj != null && obj.counter == null
or obj != null && obj.counter != null
). obj == null
或obj != null && obj.counter == null
或obj != null && obj.counter != null
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.