是否有足够的volatile来改变对列表的引用? [英] Is volatile enough for changing reference to a list?

查看:197
本文介绍了是否有足够的volatile来改变对列表的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个列表引用:

volatile List<Object> a;

现在线程1初始化它:

List<Object> newA = new LinkedList<>();
newA.add(new String("a"));
a = newA; // Write to a volatile (equivalent to exiting a synchronized block in terms of memory barriers)

然后线程2:

Object o = a.get(0); // Compound operation - first we read a volatile reference value, then invoke .get() method on it. Read to a volatile is equivalent to entering a synchronized block.

是否保证o引用线程添加的字符串1?还是我错过了什么?假设线程1的代码在线程2的代码之前执行。

Is "o" guaranteed to refer to the string added by the thread 1? Or am I missing something? Assuming that the code from the thread 1 is executed before the code from the thread 2.

推荐答案


o保证引用由线程1添加的字符串?

Is "o" guaranteed to refer to the string added by the thread 1?

如果可以保证没有其他线程间动作除非那些你明确提到的将被承诺对你的列表,然后是,你有你要求的保证。

If you can guarantee that no other inter-thread action except those you have explicitly mentioned will ever be committed against your list, then yes, you have the guarantee you are asking about.

如果任何线程在通过 volatile 变量发布后对列表进行了变异,保持更多。

If any thread mutates the list after it has been published via the volatile variable, then no inter-thread guarantees hold any more.

这篇关于是否有足够的volatile来改变对列表的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆