🧵🛠️ How to Dump Threads in Java
✅ 1. Using Command-Line Tools
🔸 A) jstack — Most Common
jstack <PID>
Dumps all thread stack traces of a running JVM.
You can get the <PID> from jps:
jps
jstack 12345 > thread-dump.txt
✅ Shows:
- Thread states (RUNNABLE, BLOCKED, WAITING)
- Locks held
- Deadlocks (with
-lflag)
✅ 2. Using Thread.getAllStackTraces() (Java Code)
If you want to dump threads programmatically:
public class ThreadDump {
public static void main(String[] args) {
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
Thread thread = entry.getKey();
System.out.println("\nThread: " + thread.getName() + " [" + thread.getState() + "]");
for (StackTraceElement element : entry.getValue()) {
System.out.println("\tat " + element);
}
}
}
}
✅ 3. Using Visual Tools
- JVisualVM (comes with JDK)
- Attach to your process
- Click “Thread Dump” button
- JConsole — basic thread monitoring
- Mission Control (JMC) — advanced profiling
✅ 4. Log a Dump on Ctrl+\ (UNIX/Linux only)
You can use kill -3 <PID>:
kill -3 12345
Dumps thread stack to the standard output (console/logs).
Safe to use anytime — doesn’t kill the process.
Thread t = new Thread(() -> { while(true) {} }, "MyCustomThread");
t.start();
🧠 Use Cases:
- Hanging or unresponsive app? 📛 Dump threads.
- Deadlock? 🔒 Look at BLOCKED threads and owned locks.
- Performance issues? 🔁 Look for RUNNABLE threads stuck in loops.