Re: Locking objects in an array
Eric Sosman wrote:
Patricia Shanahan wrote:
[...]
Synchronization with varying block sizes would be more complicated.
One way to approach it would be with recursion. I'll illustrate
with a List and an Iterator, although they're by no means the only way
to keep track:
List<Thing> things = new ...;
for (int dr = 0; dr < rspan; ++dr) {
for (int dc = 0; dc < cspan; ++dc)
things.add(lattice[r+dr][c+dc]);
}
doDirtyDeed(things.iterator(), things);
...
void doDirtyDeed(Iterator<Thing> it, List<Thing> things) {
if (it.hasNext()) {
synchronized(it.next()) {
doDirtyDeed(it, things);
}
}
else {
// all the Things' locks are now held
// do things to Things in "things"
}
}
A slightly more general variant:
static <T> void runWithSynchronization(Iterator<T> it, Runnable work){
if(it.hasNext()) {
synchronized(it.next()) {
runWithSynchronization(it, work);
}
} else {
work.run();
}
}
The Runnable can be an anonymous inner class object that has access to
the relevant data through its surrounding class. The
runWithSynchronization method can be a utility method in a separate class.
Lew's variant is the better choice if this synchronization structure is
unique to the one data structure and form of work. I would use the more
general form if I needed to do the multi-level synchronization on
multiple data structures or with different synchronized tasks.
Note that in both variants, the Iterator's order is the order of
synchronization, and must be consistent among any set of calls that
synchronize on overlapping sets of references.
Patricia