CodeGym /Courses /Java Multithreading /Strategies to avoid deadLock

Strategies to avoid deadLock

Java Multithreading
Level 7 , Lesson 5
Available
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."

Comments (5)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
matemate123 Level 50, Kraków, Poland
27 May 2023
Some additional context or a second example would be helpful. This theory seems insufficient. Too poor.
Glen Level 1, Melbourne, Australia
12 September 2025
What the code does is if two threads are running at the same time they will both try to lock the knight with the highest ID. If Thread 1 locks it then Thread 2 tries to lock it, it can't because it's already locked. Now image we didn't check the ID - Thread 1 locks knight1 but before it can lock knight2 in the nested lock Thread 2 spawns up and locks knight2. Now Thread 1 can not get a lock on knight2 and Thread 2 can not get a lock on knight1. Deadlock sir.
TheLordJackMC Level 39, Princeton, idk somewhere
4 August 2021
printers tho
Vahan Level 41, Tbilisi, Georgia
31 March 2020
Nice! It really works!
Jakub Góźdź Level 31, Katowice, Poland
19 March 2020
OMG. Brilliant! But I needed time to understand it.