Re: Synchronization Question
Knute Johnson wrote:
Patricia Shanahan wrote:
neuneudr@yahoo.fr wrote:
On Sep 14, 2:59 am, Knute Johnson <nos...@rabbitbrush.frazmtn.com>
wrote:
Lew wrote:
Knute Johnson wrote:
The OP doesn't need to synchronize for contention because of the
atomic writes of ints. He needs visibility by the reading
thread. Is
this a possible situation to use the universal visibility of volatile
write/read?
Each of the OPs array modifying threads would write to a common
volatile variable as the last action before terminating. Prior to
reading the array, the reading thread reads the common volatile
variable and all variables written to by the writing threads will be
now be visible to the reading thread.
From my re-reading Java Concurrency In Practice it is not clear
to me
either way (see pages 38,39). Not sure how one could test this.
This [1] would work, as elucidated in the JLS's discussion of
'happens-before'[2], but Patricia's suggestion of using 'join()' seems
simpler and easier.
Now that I think about it you do have a point (and so did Patricia).
[1] The array variable could be volatile, too.
A volatile array variable doesn't have volatile elements.
Can't the OP's problem be solved by using AtomicIntegerArray(s)?
It could, but that would probably be slower than just letting it fly
with an int[] and doing one memory-ordering operation for each thread,
at the end. AtomicIntegerArray would be a good solution if the OP needed
to ensure that the final result for an element is the one written by the
last thread to execute code assigning to that element.
Patricia
So you don't think that joining all the threads will ensure that the
value written by the last thread to write will be the one read?
Correct. I am most familiar with these issues on SPARC processors under
Total Store Order. They have a store buffer that holds stores that have
executed on the processor, but that have not yet been sent to the actual
memory. Stores in the store buffer are visible to code running on that
processor, but not globally visible.
Suppose Thread A, on processor 0, issues a store to element 0 of the
array, and has a significant backlog of stores, so that store does
become globally visible immediately. Shortly afterwards, Thread B,
running on processor 30, also issues a store to element 0 of the array.
Processor 30's store buffer is empty, so that one gets out immediately.
Thread B's store could appear in the global memory order ahead of Thread
A's store, despite being issued later. As far as a read after the join
is concerned, the value in memory would be the value from Thread A.
That sort of behavior is permitted by the JLS as long as there is no
happens-before relationship between the two stores.
Patricia