5

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.

Gray
  • 115,027
  • 24
  • 293
  • 354
Janek
  • 1,441
  • 2
  • 19
  • 28
  • There are probably better, more sophisticated concurrent data structures for your use, such as `CopyOnWriteArrayList`. – Matt Ball Jan 30 '14 at 19:56
  • 1
    @MattBall If this is only about communicating an effectively unmodifiable list between threads, then a plain list implementation is perfect. – Marko Topolnik Jan 30 '14 at 19:57
  • Yes it's guaranteed(Program Order Rule < Volatile Write < Volatile Read < Program Order Rule). But you should follow advice from Matt Ball. – Boris Treukhov Jan 30 '14 at 19:57

2 Answers2

9

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Just a follow up question. Is the approach from the question fine for the regular code, i.e. where ns does not count? Or I should just use a plain synchronized mechanism or suggested CopyOnWriteArrayList for the sake of readibility? – Janek Jan 31 '14 at 12:34
  • 1
    If your list doesn't change after publishing, then there is no motivation to use `COWAL`. For the sake of readability you can wrap it into an `unmodifiableList`. – Marko Topolnik Jan 31 '14 at 12:37
0

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

Kick
  • 4,823
  • 3
  • 22
  • 29