Re: Synchronization Question
Kenneth P. Turvey wrote:
I've got an array of ints:
int[][] myArray
that is written to by several threads. The threads may update the same
position overwriting each other. I don't care which value is in the
array at the end, the last thread to update it wins. The values written
are all within the range of 0 to 255.
Right now I'm synchronizing all writes to the array. This seems like the
correct way to do things, but it is eating a lot of time due to
contention. In addition, the writes to the array are not dependent on
the contents of the array. So the array is never actually read.
If it is *never* actually read, why not get rid of it completely? The
fastest write is the one that does not get done at all.
I'm going to assume that the array is not read during the operation, but
is read after it is finished.
Do I really need to synchronize these writes? If I don't is there any
risk other than a very unlikely write of a high order bit of one value
and a low order byte from another? I might be willing to accept that,
but I'm concerned that the writes interleaving might have other effects
that I'm not anticipating.
The JLS requires individual int writes to be atomic, so there is no
possibility of a mixed value from two different writes.
The key question is exactly what you mean by "the last thread to update
it wins".
At the most flexible, it could merely mean that you want the final value
of each element to be one of the values written to it if it was written,
and the original value if it was never written. In that case, you just
need to make sure that each thread does something that causes its writes
to happen-before any read of the array. For example, any write by a
thread happens-before any read that follows a join that detects its
termination.
If you really need to have the value come from the last thread to assign
to the array element, then you do need to synchronize each write.
Patricia