[concurrency-interest] Volatile array and Wait

Jeremy Manson jmanson at cs.purdue.edu
Wed Oct 19 12:32:42 EDT 2005

Shaffer, Darron wrote:
> The second option can use the volatile reference to the array as the
> "dummy".
> So given:
>   volatile Object[] b = new Object[50];
> reading looks like this:
>    Object x = b[25];  // Volatile read must occur first, to find the
> array.
> writing looks like this:
>    b[22] = x; Object dummy = b;  // Must have trailing volatile read.
> If you do this, be sure and comment it well enough that a
> junior/maintenance programmer doesn't decide that volatile applies to
> the entire array.

This won't work.  We should remind ourselves that it is important to be 
very careful when trying to use volatile for patching up our code.  It 
is really difficult to remember all of the rules, and to reason about 
them correctly.

In this case, you have to think carefully about the "acquire" and 
"release" semantics of volatiles.  A read performs an "acquire", and a 
write performs a "release".  When you are writing to memory, you have to 
perform a release.  So, in this case:

>> writing looks like this:
>>    b[22] = x; Object dummy = b;  // Must have trailing volatile read.

you need a write to a volatile field, not a read of one.  It should look 
like this:

b[22] = x;
b = b;

Or, slightly better, keep the value of the field called b in a local 

int [] arr = b;
arr[22] = x;
b = arr;


In general, you have to be very careful about using this.  I would 
suspect that in nine cases out of ten, it will not do what you want it 
to do.  For example, if you were trying to use this for a singleton, it 
would NOT be correct:

Bad Writer Thread:
b[22] = new SingletonObject();
b = b;

Bad Reader Thread:
SingletonObject so = b[22];

You could easily imagine the reader thread being scheduled between the 
two statements of the writer thread.  Guess what?  In that case, you 
don't see the effects of the volatile write.


More information about the Concurrency-interest mailing list