Quantcast
Channel: SCN : Blog List - Java Development
Viewing all articles
Browse latest Browse all 50

An example of Deadlock detection using JDK standard tool: jstack

$
0
0

We can get the concept of deadlock inwikipedia.

The picture below gives a common scenario which leads to deadlock.

http://scn.sap.com/servlet/JiveServlet/downloadImage/38-144258-983599/620-365/1.png

In this blog, I will share how to detect deadlock situation using JDK standard tool jstack.

 

First we have to write a Java program which will lead to Deadlock:

package thread;

 

public class DeadLockExample {

 

/*

  * Thread 1: locked resource 1

    Thread 2: locked resource 2

  */

public static void main(String[] args) {

  final String resource1 = "ABAP";

  final String resource2 = "Java";

  // t1 tries to lock resource1 then resource2

  Thread t1 = new Thread() {

   public void run() {

    synchronized (resource1) {

     System.out.println("Thread 1: locked resource 1");

     try {

      Thread.sleep(100);

     } catch (Exception e) {

     }

     synchronized (resource2) {

      System.out.println("Thread 1: locked resource 2");

     }

    }

   }

  };

 

  Thread t2 = new Thread() {

   public void run() {

    synchronized (resource2) {

     System.out.println("Thread 2: locked resource 2");

 

     try {

      Thread.sleep(100);

     } catch (Exception e) {

     }

     synchronized (resource1) {

      System.out.println("Thread 2: locked resource 1");

     }

    }

   }

  };

  t1.start();

  t2.start();

}

}

Execute this program, you will get output:

 

 

Thread 1: locked resource 1

 

Thread 2: locked resource 2

 

Then use command jps -l -m to list the process id of this deadlock program. In my example it is 51476:

clipboard1.png

Just type jstack + process id, and it will display all detailed information about deadlock:

clipboard2.png

Here the object 0x00000000d6f64988 and 0x00000000d6f649b8 represent the two resource String "ABAP" and "Java".

clipboard3.png


Viewing all articles
Browse latest Browse all 50

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>