Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method is the least obtrusive for generating thread dumps in java?

I am aware of the following methods for generating thread dumps in java:

  • kill -3
  • jstack
  • JMX from inside the JVM
  • JMX remote
  • JPDA (remote)
  • JVMTI (C API)

Of these methods, which is the least detrimental to the JVM's performance?

like image 703
Ovesh Avatar asked Nov 07 '14 06:11

Ovesh


People also ask

How do you create a thread dump in Java?

To take a thread dump, navigate to the console used to launch the Java application, and press the CTRL and Break keys together. It's worth noting that, on some keyboards, the Break key isn't available. Therefore, in such cases, a thread dump can be captured using the CTRL, SHIFT, and Pause keys together.

Which tool is used through which we can generate thread dump for a Java process * 1 point a JCMD B Visualvm Profiler C JCMD PID D Jstack?

jstack: Java comes with jstack tool through which we can generate thread dump for a java process.

What is Jstack in Java?

Description. The jstack command prints Java stack traces of Java threads for a specified Java process. For each Java frame, the full class name, method name, byte code index (BCI), and line number, when available, are printed.


1 Answers

If you just need to dump all stack traces to stdout, kill -3 and jstack should be the cheapest. The functionality is implemented natively in JVM code. No intermediate structures are created - the VM prints everything itself while it walks through the stacks.

Both commands perform the same VM operation except that signal handler prints stack traces locally to stdout of Java process, while jstack receives the output from the target VM through IPC (Unix domain socket on Linux or Named Pipe on Windows).

jstack uses Dynamic Attach mechanism under the hood. You can also utilize Dynamic Attach directly if you wish to receive the stack traces as a plain stream of bytes.

import com.sun.tools.attach.VirtualMachine;
import sun.tools.attach.HotSpotVirtualMachine;
import java.io.InputStream;

public class StackTrace {

    public static void main(String[] args) throws Exception {
        String pid = args[0];
        HotSpotVirtualMachine vm = (HotSpotVirtualMachine) VirtualMachine.attach(pid);

        try (InputStream in = vm.remoteDataDump()) {
            byte[] buf = new byte[8000];
            for (int bytes; (bytes = in.read(buf)) > 0; ) {
                System.out.write(buf, 0, bytes);
            }
        } finally {
            vm.detach();
        }
    }
}

Note that all of the mentioned methods operate in a VM safepoint anyway. This means that all Java threads are stopped while the stack traces are collected.

like image 74
apangin Avatar answered Nov 30 '22 15:11

apangin