What does “subsequent read” mean in the context of volatile variables?

  • A+

Java documentation says that:

A write to a volatile field happens-before every subsequent read of that same field.

I'm confused what does subsequent means in context of multithreading. Does this sentence implies some global clock for all processors and cores. So for example I assign value to variable in cycle c1 in some thread and then second thread is able to see this value in subsequent cycle c1 + 1?


It sounds to me like it's saying that it provides acquire/release synchronization between threads. See Jeff Preshing's article explaining the concept (mostly for C++, but it main point of the article is language neutral and about the concept.)

If a reader sees the value you wrote, then it knows that everything in the producer thread before that write has also already happened.

This ordering guarantee is only useful in combination with other guarantees about ordering within a single thread.


int data[100]; volatile bool data_ready = false; 


data[0..99] = stuff;  // release store keeps previous ops above this line data_ready = true; 


while(!data_ready){}     // spin until we see the write  // acquire-load keeps later ops below this line int tmp = data[99];  // gets the value from the producer 

If data_ready was not volatile, reading it wouldn't establish a happens-before relationship between two threads.

You don't have to have a spinloop, you could be reading a sequence number, or an array index from a volatile int, and then reading data[i].

(I don't know Java multithreading, just asm and C/C++, so this answer might be totally bogus. I do know that the volatile keyword in Java gives you memory ordering (sequential consistency I think), unlike C++'s volatile keyword. In C11 the equivalent keyword is _Atomic, and in C++ it's the std::atomic<T> class.)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: