【问题标题】:How to Obtain Java Thread Dump in JRE 1.8.0_144如何在 JRE 1.8.0_144 中获取 Java 线程转储
【发布时间】:2020-11-05 16:15:40
【问题描述】:
我一直在尝试寻找从运行 jre 1.8.0_144 的 Windows 服务器上的 Java 应用程序获取线程转储的方法。
jcmd jstack jconsole 等监控实用程序在 bin 或 中均不可用Java环境目录的lib文件夹。
我在网上遇到了几个声称执行相同任务但尚未找到可靠的应用程序。
感谢任何人有推荐或建议。 (不幸的是,更改 JRE 版本已被排除在外)
【问题讨论】:
标签:
java
utility
thread-dump
window-server
【解决方案1】:
如果您使用可用的 tools.jar 运行,有一种方法是从 JDK 而不是库存 JRE 运行。但是,鉴于您没有可用的 jcmd、jstack、jconsole 工具,这不太可能。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
// You need to add tools.jar to the classpath to get this
import com.sun.tools.attach.VirtualMachine;
public class Main {
public static void main(String[] args) throws Exception {
// Here you will need to use JNI or JNA to get the current process' PID
// because the JRE version you are using doesn't have any other way.
long pid = getCurrentPid(); // you need to create this method
VirtualMachine vm = VirtualMachine.attach(""+pid);
Method m = vm.getClass().getMethod("remoteDataDump", Object[].class);
InputStream in = (InputStream) m.invoke(vm, new Object[] { new Object[0] } ); // awkward due to nested var-args
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {
buffer.lines().forEach(System.out::println);
}
}
}