Thursday 7 January 2016

How to detect dead lock in java

Deadlock appearance is common scenario in multi threaded application .You must have encounter such scenario where your program gets locked while running application. There could be many reason which can cause deadlock and finding the deadlock thread is not easy . Now How to detect deadlock in your application, though this could have many answers , There are tool available to get heap dump and analyses thread to detect the deadlock.
I would explain some of the reason which can cause deadlock.
First check if there is any nested synchronize block used in your code.
calling one synchronized method from other synchronize method can also cause deadlock
another scenario could be trying to get same lock on different object .

Let us see the example which can cause deadlock and may leads to memory leak.

This is the deadlock example of nested synchronize block,



1:  class Myaccount{  
2:       public void save(){  
3:            synchronized(Object.class){  
4:                 System.out.println("Aquired lock on Object.class object");  
5:                 synchronized (Integer.class) {  
6:                      System.out.println("Aquired lock on Integer.class object");  
7:                 }  
8:            }  
9:       }  
10:       public void withdraw(){  
11:            synchronized(Integer.class){  
12:                 System.out.println("Aquired lock on Integer.class object");  
13:                 synchronized (Object.class) {  
14:                      System.out.println("Aquired lock on Object.class object");  
15:                 }  
16:            }  
17:       }  
18:  }  

If save() and withdraw() both will be called by two or many threads , there is a good chance of deadlock because if thread 1 acquires lock on Class Object  while executing save() and thread 2 acquires lock on Integer object while executing withdraw() both will be waiting for each other to release lock on Integer and Class Object to proceed further which will never happen.

Simple solution to fix above  deadlock issue is to access the synchronize block in order or sequence.


1:  class Myaccount{  
2:       public void save(){  
3:            synchronized(Object.class){  
4:                 System.out.println("Aquired lock on Object.class object");  
5:                 synchronized (Integer.class) {  
6:                      System.out.println("Aquired lock on Integer.class object");  
7:                 }  
8:            }  
9:       }  
10:       public void withdraw(){  
11:            synchronized(Object.class){  
12:                 System.out.println("Aquired lock on Integer.class object");  
13:                 synchronized (Integer.class) {  
14:                      System.out.println("Aquired lock on Object.class object");  
15:                 }  
16:            }  
17:       }  
18:  }  

Detecting Deadlocked Threads Using JConsole,

To check if your application has run into a deadlock which can causes your application to hang for infinite time . deadlocked threads can be detected by clicking on the "Detect Deadlock" button in Jconsole window.
If there is dead lock in your application then new tab Deadlock will appear beside Threads tab in jconsole window as shown  in below image.
Deadlock can be detected through java program introduced in the latest version of java.



1:  public class DeadLockTest {  
2:       /**  
3:        * @param args  
4:        */  
5:       public static void main(String[] args) {  
6:            // TODO Auto-generated method stub  
7:             ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();  
8:              long[] threadIds = threadBean.findMonitorDeadlockedThreads();  
9:              int deadlockedThreads = threadIds != null? threadIds.length : 0;  
10:              System.out.println("Number of deadlocked threads: " + deadlockedThreads);  
11:       }  
12:  }  

How to make code Thread-Safe in Java

There are multiple ways to make this code thread safe in Java:

  • Use synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes possibility of coinciding or interleaving.
  •  use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves cost of external synchronization.
  •  Immutable objects are by default thread-safe because there state can not be modified once created. Since String is immutable in Java, its inherently thread-safe.
  • Read only or final variables in Java are also thread-safe in Java.
  • Locking is one way of achieving thread-safety in Java.
  • Static variables if not synchronized properly becomes major cause of thread-safety issues.
  • Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc
  • Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an atomic operation it can't interleave with other thread.
  •  local variables are also thread-safe because each thread has there own copy and using local variables is good way to writing thread-safe code in Java.
  •  In order to avoid thread-safety issue minimize sharing of objects between multiple thread.
  •  Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.
  • use concurrent api provided by java in version 1.5.


No comments:

Post a Comment