注意:这个问题与内存可见性有关,而不是“公共(public)”、“私有(private)”等。
假设我有以下类(class):
public class Data {
public final byte[] array;
public final int offset, length;
public Data(byte[] array, int offset, int length) {...}
...
}
(上述数组中的元素可以通过未显示的方法进行更改。)
现在假设我在另一个类中有一个包含给定数据的队列:
final ConcurrentLinkedQueue<Data> queue = new ConcurrentLinkedQueue<>();
现在假设我在带有队列的类中有以下代码:
Data data = queue.poll();
... code for reading the elements in the data object.
我的问题是:在轮询队列之前设置的数组中的元素是否保证对从队列轮询数据的线程可见?
我明白队列轮询之后设置的元素对读者是不可见的,我只对队列轮询之前设置的元素感兴趣。
如果不是,我的理解是调用poll方法后放的下面的代码会保证数组的可见性
data = new Data(data.array, data.offset, data.length);
因为对象构造确保了对象字段的完全可见性。这是正确的吗?
谢谢!
最佳答案
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
所以是的,您一定会看到数组中的值,这些值是在将对象存储到队列之前设置的。 (我假设您在将数组存储到此处的队列后不会对其进行一次修改)。
关于Java 内存可见性和 AtomicReference 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676997/