Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile Variables and Happens before ordering [duplicate]

Tags:

java

volatile

I have two threads:

Thread:1

a = 1;
x = b;

Thread:2

b = 1
y = a

Here a and b are declared volatile. I did not understand how a "happens-before" edge is created between a = 1; and y = a; and between x = b; and b = 1;

I understand that by using volatile variable one can prevent reading stale values from thread cache. But how can a volatile variable ensure happens-before ordering.

Specifically, I did not understand this:

a write to a volatile field happens before every subsequent read of the same field.

Hoe does it work?

like image 824
softwarematter Avatar asked Oct 19 '10 17:10

softwarematter


People also ask

Does volatile prevent reordering?

Volatile memory operations prevent certain types of reordering with respect to the operation. A volatile write operation prevents earlier memory operations on the thread from being reordered to occur after the volatile write.

What happens when a variable is declared as volatile?

Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby.

Which is the 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.

Why do we use volatile variable?

It is used to inform the compiler that the variable value can be changed any time without any task given by the source code. Volatile is usually applied to a variable when we are declaring it. The main reason behind using volatile keyword is that it is used to prevent optimizations on objects in our source code.


1 Answers

a write to a volatile field happens before every subsequent read of the same field.

The important word here is "subsequent".

Here's the relevant bit of the Java Language Specification 17.4.4 Synchronization Order:

Every execution has a synchronization order. A synchronization order is a total order over all of the synchronization actions of an execution. For each thread t, the synchronization order of the synchronization actions (§17.4.2) in t is consistent with the program order (§17.4.3) of t. Synchronization actions induce the synchronized-with relation on actions, defined as follows:

  • [...]
  • A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order).

Note the last part. So it's saying that if you consider any total ordering of the actions of the program, any read of a volatile variable which comes later in that total ordering than a write can't "miss" the write.

like image 106
Jon Skeet Avatar answered Oct 22 '22 01:10

Jon Skeet