Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Java memory visibility 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?

like image 730
Trismegistos Avatar asked Jun 15 '18 10:06

Trismegistos


People also ask

What do you mean by volatile variable?

A volatile variable is a variable that is marked or cast with the keyword "volatile" so that it is established that the variable can be changed by some outside factor, such as the operating system or other software.

How do volatile variables work?

Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and “ main ” memory while synchronized synchronizes the value of all variable between thread memory and “ main ” memory and locks and releases a monitor to boot.

How does volatile affect variable?

The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables. It also guarantees visibility and ordering.


1 Answers

It means that once a certain Thread writes to a volatile field, all other Thread(s) will observe (on the next read) that written value; but this does not protect you against races though.

Threads have their caches, and those caches will be invalidated and updated with that newly written value via cache coherency protocol.

EDIT

Subsequent means whenever that happens after the write itself. Since you don't know the exact cycle/timing when that will happen, you usually say when some other thread observes the write, it will observer all the actions done before that write; thus a volatile establishes the happens-before guarantees.

Sort of like in an example:

 // Actions done in Thread A
 int a = 2;
 volatile int b = 3;


 // Actions done in Thread B
 if(b == 3) { // observer the volatile write
    // Thread B is guaranteed to see a = 2 here
 }

You could also loop (spin wait) until you see 3 for example.

like image 91
Eugene Avatar answered Sep 28 '22 09:09

Eugene