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.
Never read? Then why write to it?
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.
Yes, you do need to synchronize writes, otherwise there is no guarantee of the
value that will be read from another thread, nor of what write comes in "last".
Anytime multiple threads access shared data, you must synchronize all
accesses. That means both reads and writes, not just writes, and all
synchronization must occur on the same object (not the same pointer).
You might be able to stripe your locks to reduce lock contention.
ints are not written nor read a byte at a time, but an int at a time in Java.
--
Lew