Strategies to avoid deadLock - 1

"Hi, Amigo!"

"I want to tell you about a couple strategies for avoiding deadlocks."

"The best strategy is a thoughtful architecture and a set of rules governing when and in what order you can use locks (acquire mutexes). The classic approach to the problem is to develop a lock hierarchy and establish the rule that certain locks can never be acquired in a state where certain other locks have already been acquired."

"For example, sometimes locks are assigned levels, and a thread is required to acquire locks in order from higher levels to lower levels (but acquiring locks in the other direction is not allowed). Additionally, acquiring multiple locks with the same level is not allowed."

"For example, in the previous example with knights, we could add a unique number (id) to each knight and require that locks be acquired from the larger id to the smaller id."

Example
class KnightUtil
{
 public static void kill(Knight knight1, Knight knight2)
 {
  Knight knightMax = knight1.id > knight2.id ? knight1: knight2;
  Knight knightMin = knight1.id > knight2.id ? knight2: knight1;

  synchronized(knightMax)
  {
   synchronized(knightMin)
   {
    knight2.live = 0;
    knight1.experience +=100;
   }
  }
 }
}

"That'a beautiful solution."

"It's a very simple solution, but I like it. I hope it will be useful to you when you're thinking about how to solve potential deadlock problems."

"Thanks, Ellie."