Is volatile enough for changing reference to a list?

三世轮回 提交于 2019-12-23 10:19:35

问题


Let's say we have a list reference:

volatile List<Object> a;

now thread 1 initializes it:

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)

then thread 2 does:

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.

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.


回答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.

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




回答2:


YES,if Thread1 is executed before the Thread2 then it will provide the guarantee.



来源:https://stackoverflow.com/questions/21466171/is-volatile-enough-for-changing-reference-to-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!