Q:

Selectively Enforcing Synchronization to Facilitate Maximum Concurrency

Here's what I'm trying to do, with Java:
while(writeSetsIntersect()) {
    wait();
}    
doStuff    
notifyAll();

Here's where I'm stuck:  doStuff can be executed concurrently if two threads write to different variables, i.e., they have disjoint write sets.  If the write sets intersect, threads need to alternate.  So I can't simply put doStuff in a synchronized block, because it's not always (and may never be) necessary.
I could lock the items in the write set, but if two threads with intersecting write sets wait on the same lock, a deadlock could occur.  Such as:
Lock[] locks = new Lock[allAvailableVariables.length];
public void getLocks() {
    for(i = 0; i < allAvailableVariables.length; i++)
        if(i is in writeSet)
            locks[i].lock();
}

The easiest way to avoid that (as far as I can come up with) is to synchronize the acquisition of the locks in your write set.  But, if two threads with an intersecting write set are vying to get into the synchronization block, a thread with a write set disjoint from the other two would have to wait until they left the sync block.
I guess I could just have a spin lock, but I'd like to avoid that if possible, as evaluating whether the write sets intersect can be expensive.
Does this make any sense at all?

A:

Looks like you want to use lock ordering.
Sort the locks into some kind of natural order. Then lock on each in turn.
Suppose you have locks a and b with a < b. If two threads want to lock both a and b, they will both lock a first. So you can't have a situation where a thread has locked b and is blocked on a, whilst another thread has locked a is blocked on b. 

