Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is volatile enough for changing reference to a list?

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"));
// Write to a volatile
a = newA; 

then thread 2 does:

// first we read a volatile reference value, then invoke .get() method on it. 
Object o = a.get(0); 

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.

like image 585
Janek Avatar asked Jan 30 '14 19:01

Janek


1 Answers

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.

like image 165
Marko Topolnik Avatar answered Oct 05 '22 23:10

Marko Topolnik