Tuesday, 9 May 2017

How deadlock happens and how to avoid it ?


DEADLOCK SITUATION
When two threads are waiting for each other to get the lock and stuck for infinite time.
Image result for deadlock

REASON BEHIND DEADLOCK
Multiple threads are not the real cause of deadlock, instead the way in which threads are requesting the lock.
 

HOW DEADLOCK HAPPENS ?
1. When using nested synchronized blocks
OR
2. When one synchronized method called from other


ANALYZING DEADLOCK
1. Take thread dump using kill -3
OR
2. Use jconsole
It will print which thread is locked on which object.


CODE TO REPRODUCE DEADLOCK
public void m1() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
      }
  }
}

public void m2() {
  synchronized(Double.class) {
      System.out.println("inside block for Double"); 
      synchronized(String.class) {
           System.out.println("inside block for String");
      }
  } }


FIXING OR AVOIDING DEADLOCK
  • Provide ordered access to the object using synchronized blocks.
Below example will not lead to any deadlock because both methods are accessing lock on String and Double classes in same order.

public void m1() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
      }
  }
}

public void m2() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
  
      }
  }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.