Java非final(int)在构造之后可见 [英] Java non-final int(s) visible after construction
问题描述
我有一个具有非最终int变量的java类,我在构造函数中显式初始化为0.对该变量的所有其他访问由ReentrantLock管理。我不必担心线程将不会看到初始值为0,因为我没有在构造函数中使用锁。
I have a java class with a non-final int variable that I explicitly initialized in the constructor to 0. All other access to the variable is managed by a ReentrantLock. Do i have to worry that threads won't see the initial value of 0 because i didn't use the lock in the constructor?
推荐答案
是的,你必须担心。为避免出现这种情况,您需要安全地公布对象引用。
Yes, you have to worry. To avoid problems in this case you need safe publication of the object reference.
要安全地发布对象,对对象的引用和对象的状态必须可见其他
线程同时。正确构造的对象可以安全地发布:
To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
- 从静态初始化器初始化对象引用;
- 将对其的引用存储到volatile字段或AtomicReference中;
- 将引用存储到正确构造的对象的最后一个字段中;
$ b
$ b
在其他情况下,你可以(理论上)面对结果 new
在完成构造函数调用之前
In other cases you can (theoretically) face the situation when result of new
will be avaiable to other threads before completion of constructor call (due to possible operation reordering).
但是,如果 0
是一个默认值而不是写入的值在构造函数中,它会保证可见( JLS§17.4.4):
Note, however, that if 0
is a default value rather than the value written in the constructor, it's guaranteed to be visible (JLS §17.4.4):
- 将默认值(零,false或null)同步
与每个线程中的第一个动作。虽然在分配包含
变量的对象之前,向变量写入一个默认值似乎有点
,但概念上每个对象都是在
程序的开头创建的,已初始化的值
这篇关于Java非final(int)在构造之后可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!