Trigger complete stack dump programmatically?

2019-02-15 18:27发布

When I send a SIGQUIT command to my java process (using kill -3 or kill -QUIT ), it prints a trace of all stacks to stderr, with information about locks held, and deadlock detection. Can I trigger this from inside the program somehow? I want to do this automatically every time a certain operation takes too long.

I know it's possible to get a stack trace (see Is there a way to dump a stack trace without throwing an exception in java?, Thread dump programmatically /JDI (Java Debugger Interface)). But I want to see the whole everything: stack traces, thread states, locks held, locks blocked on, deadlock detection, etc., i.e. everything I get when I sent a SIGQUIT; not just the stack trace.

2条回答
虎瘦雄心在
2楼-- · 2019-02-15 19:18

Not a complete solution, but it should give you the direction:

public StringBuffer getInfoXmlString() {
StringBuffer serverInfo = new StringBuffer(3000);

serverInfo.append("<ServerInfo>");
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parent;
while ((parent = rootGroup.getParent()) != null) {
  rootGroup = parent;
}

serverInfo.append("<Threads>\r\n");
serverInfo.append(listThreads(rootGroup, "  "));
serverInfo.append("</Threads>\r\n");

serverInfo.append("</ServerInfo>\r\n");
}

private StringBuffer listThreads(ThreadGroup group, String indent) {
StringBuffer threadInfo = new StringBuffer(5000);
threadInfo.append(indent);
threadInfo.append("<ThreadGroup name=\"");
threadInfo.append(group.getName());
threadInfo.append("\" class=\"");
threadInfo.append(group.getClass().getName());
threadInfo.append("\">\r\n");

int nt = group.activeCount();
Thread[] threads = new Thread[nt * 2 + 10];
nt = group.enumerate(threads, false);

// List every thread in the group
for (int i = 0; i < nt; i++) {
  Thread t = threads[i];
  threadInfo.append(indent);
  threadInfo.append("  <Thread name=\"");
  threadInfo.append(t.getName());
  threadInfo.append("\" class=\"");
  threadInfo.append(t.getClass());
  threadInfo.append("\" alive=\"");
  threadInfo.append(t.isAlive());
  threadInfo.append("\"/>\r\n");
}
// Recursively list all subgroups
int ng = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[ng * 2 + 10];
ng = group.enumerate(groups, false);
for (int i = 0; i < ng; i++) {
  threadInfo.append(listThreads(groups[i], indent + "  "));
}
threadInfo.append(indent);
threadInfo.append("</ThreadGroup>\r\n");

return threadInfo;
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-15 19:24

Yes you can. I've been using this code successfully to debug randomly triggered concurrency bugs:

package utils.stack;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.function.Supplier;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

public interface DiagnosticCommand {
    String threadPrint(String... args);

    DiagnosticCommand local = ((Supplier<DiagnosticCommand>) () -> {
        try {
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName("com.sun.management", 
                "type", "DiagnosticCommand");
            return JMX.newMBeanProxy(server, name, DiagnosticCommand.class);
        } catch(MalformedObjectNameException e) {
            throw new AssertionError(e);
        }
    }).get();

    static void dump() {
        String print = local.threadPrint();
        Path path = Paths.get(LocalDateTime.now() + ".dump.txt");
        try {
            byte[] bytes = print.getBytes("ASCII");
            Files.write(path, bytes);
        } catch(IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

It requires Java 8 and HotSpot as the JVM as it mimics what jstack is doing, except from within the same process.

查看更多
登录 后发表回答