Doug's code was:
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; }
}
}
Bill wrote:
> Under my proposal, this would be a data race. The fact that the
> thread doing the writing does a sync is only visible to other threads
> doing a sync on the same object.
That makes sense. But I think, under your proposal, Doug could get his
memory barrier with the hackish idiom:
public void set(int i, int value) {
int[] d = data;
d[i] = value;
data = d;
}
This contains the cost of an extra write, I believe, which is probably
lower than the cost of the synchronization operation.
In fact, if we're just using the volatile variables to get at memory
barriers, something along the lines of:
class VolatileArray {
private final int[] data;
private volatile int macguffin = 0;
public VolatileArray(int cap) { data = new int[cap]; }
public int get(int i) {
return data[i + macguffin];
}
public void set(int i, int value) {
data[i] = value;
macguffin = 0;
}
}
would probably have to work. It makes get() a little more expensive,
but eliminates the need for a read barrier in set(). Even compilers
which detected that the macguffin variable was unused would need to
preserve the memory barriers.
I need to go shower now.
--p
-------------------------------
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