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

查看:12
本文介绍了哪种方法在 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?

推荐答案

如果你只需要将所有堆栈跟踪转储到 stdoutkill -3jstack 应该是最便宜的.该功能在 JVM 代码中本地实现.没有创建中间结构 - 虚拟机在遍历堆栈时会自行打印所有内容.

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 上或 Named Pipe 在 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 在底层使用 Dynamic Attach 机制.如果您希望将堆栈跟踪作为纯字节流接收,也可以直接使用动态附加.

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天全站免登陆