何时 http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight说
The values for an object's final fields are set in its constructor. Assuming the object is constructed "correctly", once an object is constructed, the values assigned to the final fields in the constructor will be visible to all other threads without synchronization. In addition, the visible values for any other object or array referenced by those final fields will be at least as up-to-date as the final fields. What does it mean for an object to be properly constructed? It simply means that no reference to the object being constructed is allowed to "escape" during construction.
这是否意味着只有看到不正确构造的对象的线程可能会看到它处于错误状态,但所有其他线程都很好?
例如,假设您有一些简单的代码
public class Foo {
final int x = 5;
public Foo() {
new Thread(() -> System.out.print(x)).start();
}
}
这是否意味着只有看到隐式 this
引用的线程可能存在可见性问题,但使用 Foo 实例的任何其他线程都保证看到完全可见的 Foo 引用它的字段x
是5?
最佳答案
JLS州,
An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's
final
fields.
没有迹象表明一个线程的可见性保证会受到另一个线程的不安全发布的影响。
关于java - 不正确构造的对象是否只影响它在构造函数内发布的线程的可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070722/