Sobes.tech
Middle+

How to get a stream dump in Java?

sobes.tech AI

Answer from AI

Getting a thread dump in Java can be done in several ways.

Command-line tools

  1. jstack <pid>: The most common method. Requires the PID of the Java process.

    # Get process PID (Linux)
    # ps aux | grep <process_name>
    
    # Get thread dump
    jstack <PID>
    
  2. jcmd <pid> Thread.print: A newer, versatile tool.

    jcmd <PID> Thread.print
    
  3. kill -QUIT <pid> (Linux/macOS): Sends the QUIT signal to the process, which results in a thread dump being printed to standard output or the application's log file.

    kill -QUIT <PID>
    

GUI tools

  1. JConsole: Connect to the process, go to the "Threads" tab, and click "Export Thread Dump".
  2. VisualVM: Connect to the process, double-click it, then click the "Thread Dump" button.

Programmatic method

You can obtain a dump programmatically using the JMX API (java.lang.management.ThreadMXBean). This is useful for integration with monitoring tools or for obtaining a dump under certain conditions.

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ThreadDumpExample {

    public static void main(String[] args) {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true); // true: dump stack, true: lock info

        for (ThreadInfo threadInfo : threadInfos) {
            System.out.println(threadInfo.toString());
        }
    }
}

A thread dump shows the state of each thread in the JVM, including its call stack, state (RUNNABLE, WAITING, TIMED_WAITING, BLOCKED), and lock information (monitors and synchronizers), which is critical for debugging performance issues, deadlocks, and lock contention.