Capturing a thread dump
Thread dump is a snapshot of all the threads that were executing at a moment in time. It shows the stack trace of each thread, the locks they have obtained, locks on which they are waiting, their priority, current java memory utilization by each space… In nutshell it’s a vital artifact to diagnose any Java memory, CPU related related problems.
Here is how one would capture thread dump:
Step 1: Identify the Process Id
First you need to identify the Java Process Id, for which you need to capture thread dump. For this purpose, you can use “jps” (JVM Process Status) tool that is shipped in JDK. This tool list all the Java processes that are running on the target system and their process Id.
jps
Below is the sample output of executing this command:
30548 org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar 36292 Jps 37320 AddressBook
First field in each line is the process Id and second field is the name of the Java program that is running. As per the above example ’37320′ is the process Id of the AddressBook program.
Alternatively if you are running on *nix operating system, you can also issue “ps” (process status) command and grep for java processes. Example:
ps -ef | grep 'java'
Step 2.a: Capture Thread Dump in *nix
‘jstack’ is an effective tool to capture thread dumps. jstack tool is shipped with JDK. Here is the command that you need to issue to capture thread dump:
jstack -l <pid> > <file-path>
where
pid: is the Java Process Id, whose thread dump should be captured
file-path: is the file path where thread dump will be written in to.
Example:
jstack -l 37320 > /opt/tmp/AddressBook-threadDump.txt
Now thread dumps would be generated in /opt/tmp/AddressBook-threadDump.txt file.
I have seen in major enterprises for security reasons only JREs are installed in production machines. Since jstack is part of JDK, you wouldn’t be able to use jstack tool. In such circumstances ‘kill -3’ option can be used.
kill -3
When ‘kill -3’ option is used thread dump is sent to standard error stream.
Step 2.b: Capture Thread Dump on Windows
Even though ‘jstack’ is shipped in JDK, it doesn’t work that well in Windows. So recommended way to generate Thread dump on windows machine is to use the ‘jvisualvm’ tool. This tool is also shipped with JDK. Here are the steps:
a. Launch the Visual VM tool
Click on jvisualvm.exe on %JAVA_HOME%bin folder.
b. Select your application
Once you launch the jvisualvm, on the left panel you will notice all the java applications that are running on your machine. You need to select your application from the list