What is a Deadlock ?
It is a condition where two or more threads are blocked forever because they are waiting for each other to get the lock/resource. And it happens because of the inappropriate use of mutual exclusion locks.
So let's see a sample of code where a deadlock situation is created intensionally for demonstrate purpose.
Output :Here you can observe both th threads are waiting for each other to get the lock.
How to detect deadlock threads in your application?
Well, so Java has given default tools with the JDK package; using those we can detect the thread dumps which are in deadlock state. And also there are so many 3rd party tools available in market you can use for the same.
Here we will discuss about Java's default tool and how programmatically we can detect deadlock.
Detect deadlock programmatically :
OK, so let's create a daemon thread which runs in background and detects if there is any deadlock thread and prints.
This is a thread which runs in background as daemon thread till the JVM is alive and repeatedly detects deadlock in every 5 seconds.
Java 5 introduced new classes under package java.lang.management
ThreadMXBean : The management interface for the thread system of the Java virtual machine.
ManagementFactory : This is a factory class to get ThreadMXBean instance.
ThreadInfo : This class contains basic thread info like thread ID and thread name.
Now let's add the detector thread to the main program :
Output:
Detect deadlock using Java's default tools :
Using jconsole :
Java has provided jconsole tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jconsole
Step 2 : Select process name with PID and click Connect
Step - 3 : Select Thread tab and click Detect Deadlock
Final output window:
Using jstack :
Java has provided jstack tool in .../<jdk_home_dir>/bin
Step - 1: ../bin/$ jstack <PID>
Ex : ../bin/$ jstack 17472
Output:
That's all for this post.
Please feel free to give your comment/suggestion. Thank you.
No comments:
Post a Comment