RE: JavaMemoryModel: Volatile array references

From: David Holmes (
Date: Tue Apr 30 2002 - 23:27:11 EDT

Bill Pugh wrote:
> Unfortunately, there is no way in the Java type system to have the
> elements of an array be volatile. You can have a volatile field that
> contains a reference to an array, but that isn't the same thing.

Right - I realize that. I was just thinking if having a volatile array
reference causes some of the volatile properties to spill over to the
elements. But I'm not thinking clearly enough.

> If you want to get the effect of an array with volatile elements,
> have an extra volatile dummy field associated with the array. After
> each write to an array element, write to the dummy field (it doesn't
> matter what value is written).

Right - that's the bit that's missing. Reading the array reference doesn't
help with "flushing" the element value.

> Before each read of an array element, read the dummy field (and discard
the value).

Surely the read of the volatile array reference itself would suffice for

So rethinking what I'm trying to do (which is read from an array without
using a lock) the following should suffice:

volatile int[] array = ...;

   Thread 1 Thread 2

   synchronized(array) {
       array[0] = 10;
                                       int x = array[0];

Now we should be guaranteed to have x = 10 - right? The locking in thread 1
forces array[0] to be visible, and the read of the volatile array ref forces
the read of array[0] to be done from main memory.

As for syntax (in reference to Cliff's post):

 volatile int[] array;

is a normal declaration of a volatile variable that happens to reference an
array type. The invalid syntax was the mooted:

  int[] volatile array;


JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:39 EDT