At 1:27 PM +1000 5/1/02, David Holmes wrote:
>
>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.
You are still thinking in terms of memory barriers:
"The locking in thread 1 forces array[0] to be visible"
Don't. There are no memory barriers. Just "happens-before"
(conversely "happens-after") relations.
The read of the volatile field named array "happens-after" other
writes to the volatile field named array. If you want the read of the
field named array to be the memory coherence action performed by the
reader, then the writer would need to perform:
Thread 1:
array[0] = 10;
array = array;
It would be a little more efficient for thread 1 to keep the value of
the field named array cached in a local variable:
Thread 1:
int [] a = array;
a[0] = 10;
array = a;
--- Bill ------------------------------- JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:39 EDT