
Deadly embrace
I think any OS class student remembers the "Chinese philosophers" problem. Anyway this problem represent only one format of deadlocks a.k.a deadly embrace.
In contrary to Java, database servers detect and resolve deadly embraces by using a graph that nodes transaction and edges represent the A needs a lock that B is holding, if there is a circle in this graph, then a deadly embrace has happened.
**: my first thought on this problem was that: why not they try to eat with only one chopstick, you agree that it's better than starving, we 'll get to this solution later as a general solution to avoid deadlock, just read on ;)
Lock-ordering Deadlocks:
Consider this priece of code :
| // Waning: deadlock-prone! Public class LeftRightDeadlock { Private final Object left = new Object(); Private final Object right= new Object(); Public void leftRight() { Synchronized (left) { Synchronized (right) { Dosth(); } } } Public void rightLeft() { Synchronized (right) { Synchronized(left) { Dosth(); } } } |
As you can see, these two methods can cause deadlock, because:
in general :
A program will be free of lock-ordering deadlocks if all threads acquire the locks they need in a fixed global order.
To add to this I want to mention that problems are not always as clear as our sample, just consider the case that there is a method that lock orders is based on its first parameter and then second parameter, in this case if the passed attribute changes in two seperate calls, the same non-global order will raise, using a rule for acquiring locks that make it independent of order of varaibles is the right solution(ex. using a general comparison method [a global method] to indicate lock orders).
**: Another solution can be wrapping the sequence of locks with a 3rd lock as a tie breaker, but this solution basically cause a concurrency bottleneck and again it is using only one lock instead of having two seperate locks.
For more reading, look at this javaWorld article.
Multiple lock acquisition is not always happening in the same method.Invoking an alien method from a method that has held a lock is asking for liveness trouble. The alien method might acquire other locks (risking deadlock) or block for an unexpectedly long time, stalling other threads that need the lock you hold.
Alien method :Methods that their behavior is not fully specified by this class (non private, non-final methods of the same class [ they are overrideable] and methods of other classes