> so the change you are suggesting is that "volatile", when applied to arrays,
> means that the elements of the array are volatile, in addition to the reference
> to the array?
No, this would be problematic, as you note.
Instead, I am observing that indexing off volatile arrays always gives
you read barriers on element access, but never automatically gives you
write barriers on element writes. To get the write barriers, you need
synchronization. The net effect is that, if elements of a volatile
array are always updated under synchronization, then they are
readable, through that array reference, without synchronization.
Here's the example again, removing "final" to avoid syntax issues.
class VolatileArray {
private volatile int[] data;
public VolatileArray(int cap) { data = new int[cap]; }
public int get(int i) {
int[] d = data;
return d[i];
}
public void set(int i, int value) {
int[] d = data;
synchronized(d) { d[i] = value; }
}
}
Informally, here's what happens in get():
1. A read barrier (on machines needing one) is performed before:
int[] d = data;
Also, since it is volatile, the compiler is not
allowed to act as if it already knows the value of "data".
So both the machine and the compiler must cooperate about this part.
2. The element is read at the given offset (maybe after a bounds
check).
Again, both the compiler and machine must comply with intent:
Because of the dependency on the volatile read of "data",
the compiler is not allowed to act as if it knows anything about
that element beforehand and so cannot reuse old values.
And because we've just done a read barrier, the read must be
seeing the most recently committed value of the element.
The synchronization in set() ensures that these writes are
committed. So here, we assured of seeing result of last completed
set().
Does anyone see any problem in this reasoning? If not, the memory
model should support it.
Because JLS does not talk explicitly about read barriers wrt
volatiles, it doesn't quite say that this will happen, but it does
happen.
I'm less sure about whether Bill's LC proposal covers this case.
The normal disclaimer: This is not an idiom "for the masses". But
it does fill in an existing gap in order to allow safe lock-free
concurrently readble data structures to be implemented.
-Doug
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:23 EDT