Saturday, December 29, 2012

How To Detect DeadLocks In Java Programs/Applications usin JConsole Java Utility (A Quicker Way)

DeadLock is a situation where two or more threads are blocked forever waiting for each other. So your Java program or Java Application freezes and you need to force close or kill the application by yourself. Since not all the times the dead Lock causes your application to freeze, we need to first identify if the application has crashed is really due to deadLock or some other reason. To find out if your application is caused due to deadlock situation, its fairly simple. The JDK (Java Development Kit) already provides a Utility called jConsole which is a Monitoring Tool and a management console which has ability to connect to remote VMs and analyze the thread dumps of your running java application. jConsole also gives the summary of the usages of heap memory, Eden Space, Survivor, Tenured Gen, etc usage in graphical format.  It also gives information about number of classes loaded, threads loaded and other important data of your application including the deadlock situations amongst threads if any.

I'll show you how we can use jConsole application and connect to a sample java program that has encountered deadlock and thus has blocked.

1. Open the jConsole application which is present in your %JAVA_HOME%\bin directory (Your Java installation directory) using command prompt or just double clicking on jConsole.exe program
2. When you open jConsole, it displays the name and process IDs of the running applications, choose your java application name that is suffering from deadlock situation as shown in the following screenshot (DeadLockTest is my Java Application which is blocked forever due to deadlock in below image)

  

3. Once selected your application, click Connect.
4. Click on the 'Threads' tab and then on 'Detect DeadLock' button at the bottom of the screen as shown in the following screen shot.

 
5. Once you click on Detect Deadlock button in red color in above screenshot, the threads that are 'dead locked' will be displayed with complete stack trace as shown in the following screen shot.
6. By selecting a particular thread, the stack trace is displayed in the right side of the screen which can be used to analyze the deadlock situation and resolve the issue.
 In above example, I have two threads Thread-1, Thread-0 that are waiting for each other.

If there are no deadlocks, then under 'DeadLock' No threads will be listed.

jConsole really comes handy while debugging java prorams, it could be debugging deadlocks, or doing memory optimizations, etc.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...