Techie Hints

A place where to find tech solution

What is Dead Lock ?

Dead Lock

When two or more threads are waiting for each other to release lock and get stuck for infinite time, situation is called deadlock . It will only happen in case of multitasking.


Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever



I can give you one realistic comparison for this explanation:

During my work I was trying to edit a excel in sharepoint it was restricted such a way one person can edit at a time unfortunately the same file was opened by one of  onsite colleague in edit mode before his vacation starts, I was stuck without aware of it and couldn’t update the tasks sheet until he comes.

You can compare above scenraio to understand how dead locak can happen between threads.


Java Code Example for Dead Lock situation.

/** * Java program to create a deadlock by imposing circular wait. * */
public class DeadLockDemo {

/* * This method request two locks, first String and then Integer */

public void method1() {

synchronized (String.class) {

System.out.println(“Aquired lock on String.class object”);
synchronized (Integer.class) {

System.out.println(“Aquired lock on Integer.class object”);

}

}

}

/* * This method also requests same two lock but in exactly * Opposite order i.e. first Integer and then String. *
This creates potential deadlock, if one thread holds String lock * and other holds Integer lock and they wait for each other, forever. */
public void method2() {

synchronized (Integer.class) {

System.out.println(“Aquired lock on Integer.class object”);
synchronized (String.class) {
System.out.println(“Aquired lock on String.class object”);
}

}

}

}

How to avoid this scenario ?

Here is the example.

public class DeadLockFixed {

/** * Both method are now requesting lock in same order, first Integer and then String. * You could have also done reverse e.g. first String and then Integer, * both will solve the problem, as long as both method are requesting lock * in consistent order. */
public void method1() {

synchronized (Integer.class) {

System.out.println(“Aquired lock on Integer.class object”);
synchronized (String.class) {

System.out.println(“Aquired lock on String.class object”);

}

}

}

public void method2() {

synchronized (Integer.class) {

System.out.println(“Aquired lock on Integer.class object”);

synchronized (String.class) {

System.out.println(“Aquired lock on String.class object”);
}
}

}

}

 

%d bloggers like this: