gpt4 book ai didi

java - final vs volatile guaranntee w.rt 安全发布对象

转载 作者:搜寻专家 更新时间:2023-10-30 19:43:40 26 4
gpt4 key购买 nike

摘自《Java 并发实践》一书:

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:

  • Initializing an object reference from a static initializer

  • Storing a reference to it into a volatile field or AtomicReference

  • Storing a reference to it into a final field of a properly constructed object

  • Storing a reference to it into a field that is properly guarded by a
    lock.

我的问题是:

  1. 要点 2 和 3 之间有什么区别?我对 volatile 方法和 final 方法在安全发布对象方面的区别很感兴趣。
  2. 他在第 3 点中正确构造的对象的最终字段是什么意思?在开始要点之前,作者已经提到他们正在谈论一个正确构造的对象(我假设这不会让 this 引用 escape )。但他们又一次提到了正确构造的对象的原因?

最佳答案

What are the the differences between bullet points 2 and 3 ?

  • volatile 基本上意味着对该字段的任何写入都将从其他线程可见。因此,当您将一个字段声明为 volatile 时:private volatile SomeType field;,您可以保证如果构造函数写入该字段:field = new SomeType();,这分配将被随后尝试读取 field 的其他线程可见。
  • final 具有非常相似的语义:您可以保证如果您有一个 final 字段:private final SomeType field; 对该字段的写入(无论是在声明中或在构造函数中):field = new SomeType(); 不会被重新排序并且将被其他线程可见如果对象被正确发布(即没有逃逸这个例如)。

很明显,主要的不同是如果字段是final,你只能分配一次。

What does he mean by final field of a properly constructed object in point 3 ?

例如,如果您让 this 从构造函数中逃逸,最终语义提供的保证就消失了:观察线程可能会看到具有默认值的字段(对于对象为 null) .如果对象构造正确,则不会发生这种情况。


人为的例子:

class SomeClass{
private final SomeType field;

SomeClass() {
new Thread(new Runnable() {
public void run() {
SomeType copy = field; //copy could be null
copy.doSomething(); //could throw NullPointerException
}
}).start();
field = new SomeType();
}
}

关于java - final vs volatile guaranntee w.rt 安全发布对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com