哪种方法在Java中生成线程转储最不麻烦? [英] Which method is the least obtrusive for generating thread dumps in java?

查看:64
本文介绍了哪种方法在Java中生成线程转储最不麻烦?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下用于在Java中生成线程转储的方法:

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

  • 杀死-3
  • jstack
  • 来自JVM内部的JMX
  • JMX远程
  • JPDA(远程)
  • JVMTI(C API)

在这些方法中,对JVM性能的危害最小吗?

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

推荐答案

如果只需要将所有堆栈跟踪转储到 stdout ,则kill -3jstack应该是最便宜的.该功能在JVM代码中本地实现.不会创建任何中间结构-VM在遍历堆栈时会自行打印所有内容.

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.

这两个命令执行相同的VM操作,除了信号处理程序在本地将堆栈跟踪打印到Java进程的 stdout ,而jstack通过IPC接收目标VM的输出( Unix域Linux上的套接字或Windows上的命名管道).

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在后台使用了动态附加机制.如果希望以纯字节流的形式接收堆栈跟踪,也可以直接使用动态附加.

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();
        }
    }
}

请注意,所有提及的方法无论如何都在VM安全点中运行.这意味着在收集堆栈跟踪时,所有Java线程都将停止.

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.

这篇关于哪种方法在Java中生成线程转储最不麻烦?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆