Saturday, July 30, 2016

Deadlock in Java

csunplugged.com


When we talking about threads, Deadlock is another important thing. If you are a beginner, this may be very useful when you face an interview.


What is called Deadlock ?

Deadlock is caused by multiple threads are blocked and waiting for each other to release the lock of the object.If you want to know about that Lock of object, please refer this post.

At the time they are waiting each other forever. Look at the following code. Then you may understand it.


ParentClass.java

package com.app;

public class ParentClass {
   final String s1 = "A";
   final String s2 = "B";
}


ThreadOne.java

package com.app;

public class ThreadOne extends ParentClass implements Runnable{

   public void run(){
       synchronized (s1) {
           System.out.println("ThreadOne s1");
           try{
               Thread.sleep(100);
           }catch (Exception e){ }
           synchronized (s2){
               System.out.println("ThreadOne s2");
           }
       }
   }
}


ThreadTwo.java

package com.app;

public class ThreadTwo extends ParentClass implements Runnable {

   public void run(){
       synchronized (s2){
           System.out.println("ThreadTwo s2");
           try{
               Thread.sleep(100);
           }catch (Exception e){ }
           synchronized (s1){
               System.out.println("ThreadTwo s1");
           }
       }
   }
}


Application.java

package com.app;

public class Application {

   public static void main(String[] args){
       Thread t1 = new Thread(new ThreadOne());
       Thread t2 = new Thread(new ThreadTwo());
  
       t1.start();
       t2.start();
   }
}



Sometimes it looks complex, but it is easy to understand. When you run this, you may get one of following results.

ThreadOne s1 
ThreadTwo s2 

or

ThreadOne s2
ThreadTwo s1

Deadlock is critical  

It is very difficult to test for deadlocks. You may know that, testing a multithreaded application is very difficult task. This the main disadvantage of using threads. Then you can understand about the situation with Threads + Deadlocks. 

Because deadlocks depend on system, environment, underlying hardware etc.

What is caused for deadlocks ?

Mainly deadlocks are caused by inconsistent lock ordering of objects. If you have any idea to detect deadlocks it may help you to prevent deadlocks.

How to prevent a deadlock ?

  • Use multi-threads, only if it is must
As you know, if you use multi threads; it makes your code more complex. So you can choose multi threading only if you want in your application. More info

  • Order locks
If you can arrange your locks according to an order, then it will avoid conflicts with each locks. So what you can do is; assign a numeric values to each lock and you should order them according to the priority of those locks. 

But you should have a good understand about locks and when they are needed for each other.

  • Set lock timeout 
You can set timeout to remove conflicts between locks. You can build the mechanism to rebuild to application for random timing if it detects a deadlock. Then it will run continuously without giving any chance to deadlocks. 

  • Keep lock private (Encapsulate locks)
Make locks private, then complete control is in your hand. Don't share data between threads if it is not necessary.

  • Look for other alternative ways
You can use volatile fields, then it doesn't require lock and multiple threads can access the latest value of the field.

  • Focus about deadlocks in application design time
This may be help to avoid deadlocks because deadlocks are unpredictable at sometimes. If you study more about the system in design time it may help you to avoid deadlocks.


  • Always try to shrink synchronization blocks or methods

This may help to make your design easier to it will make easy to understand about potential deadlocks. Because it is easy to check in small blocks rather than huge blocks.