We’ll explore how to capture a thread dump and analyze it effectively in this post. This is a continuation of Java Dumps Uncovered: When to Use Thread Dump, Heap Dump, or Core Dump.
Quick Summary
A thread dump helps determine if a thread is stuck. However, taking a single thread dump isn’t enough—we need at least two or more dumps to confirm whether a thread remains in the same state over time.
Ways to Capture a Thread Dump
There are multiple ways to take a thread dump. We’ll explore each method using a sample Java program that creates two threads—one terminating in 30 seconds and another in 5 minutes. The Java file is available in this gist.
To capture a thread dump, the first step is to identify the Java process ID (PID). This can be done using:
$ jps
or
$ ps aux | grep java
This command lists all running Java processes. Select the PID of the process for which you need the thread dump.
1) Using jstack or jcmd
The jstack command prints the thread dump of a running Java process:
$ jstack <PID>
To save the output to a file:
$ jstack <PID> > threaddump.txt
Alternatively, the jcmd command can be used:
$ jcmd <PID> Thread.print
Or to save it to a file:
$ jcmd <PID> Thread.print > threaddump.txt
The thread dump appears in the same directory where the command is executed.
2) Using kill -3 (Linux/macOS)
This method sends a SIGQUIT signal to the JVM, causing the thread dump to be written to the application’s standard error output (stderr) or logs:
$ kill -3 <PID>
The thread dump appears in the console output or application logs.
3) Using VisualVM
To capture a thread dump using VisualVM:
- Start VisualVM (
jvisualvmcommand). - Select the Java process for which the thread dump is needed.
- Click on Applications from the menu bar and select Thread Dump.
4) Using jconsole
To capture a thread dump with jconsole:
- Start jconsole from the terminal.
- Choose the application from Local Processes or connect to a remote machine.
- Navigate to the Threads tab.
- View all running threads in the left panel.
- If a thread has been running for an extended period, click on it to view the thread dump.
Which Method to Use?
In most cases, jstack/jcmd and kill -3 are preferred since VisualVM and jconsole cannot connect to production machines due to security restrictions.
Additionally, tools like Java Mission Control can capture thread dumps. Some application servers like Tomcat, WebLogic, and WebSphere provide admin tools to generate thread dumps, but disabling these tools is recommended for security reasons. 😉
Conclusion
Understanding how to take a thread dump is essential for diagnosing application issues. Whether using jstack, jcmd, kill -3, VisualVM, or jconsole, selecting the right method depends on the environment. Capturing multiple dumps and analyzing them carefully can help identify stuck threads and performance bottlenecks, ensuring smoother application performance. 🚀

Comments
Post a Comment