[concurrency-interest] about Volatile reads/writes

Jeremy Manson jmanson at cs.purdue.edu
Tue May 23 22:19:53 EDT 2006


yangjs wrote:
> how to explain the follow sentence?
> 
> Volatile reads/writes cannot be reordered
> Reads/writes become acquire/release pairs

As the speaker for that particular slide, I hate to seem flip, but it 
means what it says.

1) Volatile accesses cannot appear to have been reordered with each 
other.  For example, let's say I have two volatile boolean fields, v1 
and v2, and the following code running in one thread:

v1 = true;
v2 = true;

And the following code running in another:

if (v2)
   assert v1;

The assertion is not allowed to fail.  If the accesses in the first 
thread were reordered, then the assertion could fail - the second thread 
could see v2 being true before it sees v1 being true.

2) A read of a volatile acts like an acquire, and a write to a volatile 
acts like a release.  There is therefore a happens-before relationship 
between a write to a volatile and a read of a volatile.  In the example 
above, this implies that the assertion can't fail even if v1 is not 
volatile, as long as v2 is volatile.

I suggest you read the JSR-133 FAQ for more information:

http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

Especially the sections on what synchronization does and what volatile 
does.  Better still, run over to amazon.com and get yourself a copy of 
Java Concurrency in Practice.


					Jeremy


More information about the Concurrency-interest mailing list