java - 不正确构造的对象是否只影响它在构造函数内发布的线程的可见性?

标签 java multithreading concurrency visibility safe-publication

何时 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/

相关文章:

linux - pthread 互斥体解锁如何工作?线程是否同时出现?

concurrency - LMAX 的颠覆者模式如何运作?

linux - 路径查找和写入并发问题

java - 尝试在 OS X 中使用 JPL 和 YAP Prolog 时抛出异常

java - 在 Java 中将 ExecutorService 变成守护进程

java - 如何忽略一个实体中的属性而不忽略另一个实体中的属性 - JSON

java - 限制一个java命令的线程数

ios - 序列化 NSURLConnection 请求 (iOS) - 使用同步请求?

java - Java中如何获取两个n维数组的和?

java - Android 在启动应用程序时出现运行时错误