How to get Java Call Stack of a running application

妖精的绣舞 提交于 2019-11-28 06:58:19
Mikhail Vladimirov

Method 1: Use jstack utility from command line (part of the JDK distro).

Method 2: Send signal 3 to the java process, it will dump stack traces on stdout.

Method 3: Call Thread.getAllStackTraces () from within application:

public class StackTraceDumper
{
    public static dumpAllStackTraces ()
    {
        for (Map.Entry <Thread, StackTraceElement []> entry: 
            Thread.getAllStackTraces().entrySet ())
        {
            System.out.println (entry.getKey ().getName () + ":");
            for (StackTraceElement element: entry.getValue ())
                System.out.println ("\t" + element);
        }
    }
}

Then use StackTraceDumper.dumpAllStackTraces() where you need to dump stack traces.

Thread.dumpStack() Prints a stack trace of the current thread to the standard error stream. Thread.getAllStackTraces() Returns a map of stack traces for all live threads. Thread.getStackTrace() Returns an array of stack trace elements representing the stack dump of this thread.

Graham Borland

Have a look at Throwable.getStackTrace(). Just create a new Throwable; you don't actually have to throw it.

Brian Agnew

You can trigger a stack dump via pressing Ctrl+Break, or sending a signal 3 (on Unix-based systems). Note that you'll get a stack trace per-thread. This will go to standard error, so make sure your logging is capturing this.

You can do this programatically via

Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();

Here's more info on getting and analysing stack traces.

As you've noted, BTrace is another possibility. Here's an SO answer on using it.

There are some options:

  • Run it in a debugger, and pause all threads, then you can inspect them
  • Use VisualVM to connect to the running processes and trigger a thread dump. It comes with the JDK.
  • Use jstack on the command line, to dump threads.

Add some basic logging to your code:

new RuntimeException().printStackTrace();

That will pring a static trace to stderr

Why don't you use some AOP tool like AspectJ to capture these values and log? You can use execution() point cut along with after() advice. For non production deployment you can log all the method calls along with passed values and returned value. This will be too much overhead for production env. For that you can just store the passed values (Object args[] as you get in AspectJ advice) in local variable and only log it in case of exception. But even in that case there will be some performance penalty as primitive values will be boxed to be passed as Object[] to your advice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!