6

when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change

This is mentioned at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

Can someone please provide an example of this?

This first gave me an impression that the thread that reads a volatile variable will synchronize with the writer thread and wait until the write is done. But that clearly is not the case.

An example would help a lot and be much appreciated.

Thanks, Mustafa

Asif
  • 1,288
  • 1
  • 16
  • 27
  • Volatile fields *do* establish a [synchronization order](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.4): "A write to a volatile variable v (§8.3.1.4) synchronizes-with all subsequent reads of v by any thread (where "subsequent" is defined according to the synchronization order)." However, this *does not* mean that an arbitrary write will occur before an arbitrary read (the order is established as the *result* of a write). – user2864740 Nov 02 '13 at 03:32

2 Answers2

12

Let's say you have the following class:

public class Shared {
    public int a;
    public int b;
    public volatile int c;
}

Now let's say that thread A has a reference to an instance of this class and does

shared.a = 1;
shared.b = 2;
shared.c = 3;

And let's say that thread B has a reference to the same instance and does

display(c);
display(b);
display(a);

Then, if the value displayed for c is 3 (i.e. if the write of thread A has happened before the read of thread B), then it's guaranteed by the Java memory model that 2 and 1 will also be displayed for b and a respectively, because all the actions of thread A that have been made prior to the write to the volatile c are guaranteed to be visible by a thread that has read the new value of c.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks. The statement makes much more sense now. For now my purpose is served. Mush appreciated. – Asif Nov 02 '13 at 15:46
0

As I understand the text of the document, if the volatile modifier is applied to the field, then it guarantees the following: if the volatile-field is changed in the code, then this change will occur after all operations preceding it, and before all operations, following it, and this will be the case for all application threads.