How do you get a thread dump in Java?

A thread dump is a snapshot of every thread running inside a JVM at a given moment, showing each thread's state and stack trace, and it's the primary diagnostic tool for investigating deadlocks, hangs, and performance bottlenecks in a running Java application.

Key Points: • jstack <pid>, bundled with the JDK, is the most common command-line way to capture a thread dump for a running process. • Sending a SIGQUIT signal (Ctrl+\ on Unix/Linux, Ctrl+Break on Windows) to the JVM process prints a thread dump directly to its console/log output. • jcmd <pid> Thread.print is the modern JDK tool recommended over jstack in newer JDK versions. • A thread dump reports each thread's name, state (RUNNABLE, BLOCKED, WAITING, TIMED_WAITING), and full stack trace, and explicitly flags detected deadlocks. • Taking multiple thread dumps a few seconds apart is a common technique for spotting threads that are consistently stuck at the same point, indicating a real bottleneck rather than a momentary snapshot artifact.

Example: When a production service appears to hang, running jstack <pid> (or jcmd <pid> Thread.print) captures the exact stack trace of every thread, letting you see, for instance, that several threads are all BLOCKED waiting on the same lock held by one thread stuck in a slow database call.

Interview Tip: A concise interview answer is:

"I'd take a thread dump with jcmd <pid> Thread.print or the older jstack <pid> tool, both bundled with the JDK, or by sending a SIGQUIT to the process to print it to the console. It gives every thread's state and stack trace at that moment, which is exactly what you need to diagnose a hang or deadlock."