Is there a way to dump a stack trace without throwing an exception in java?

前端 未结 10 1386
庸人自扰
庸人自扰 2020-12-04 07:37

I am thinking of creating a debug tool for my Java application.

I am wondering if it is possible to get a stack trace, just like Exception.printStackTrace()

相关标签:
10条回答
  • 2020-12-04 08:16

    If you need capture output

    StringWriter sw = new StringWriter();
    new Throwable("").printStackTrace(new PrintWriter(sw));
    String stackTrace = sw.toString();
    
    0 讨论(0)
  • 2020-12-04 08:20

    Java 9 introduced the StackWalker and supporting classes for walking the stack.

    Here are a few snippets from the Javadoc:

    The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream. The stream reports stack frame elements in order, from the top most frame that represents the execution point at which the stack was generated to the bottom most frame. The StackFrame stream is closed when the walk method returns. If an attempt is made to reuse the closed stream, IllegalStateException will be thrown.

    ...

    1. To snapshot the top 10 stack frames of the current thread,

      List<StackFrame> stack = StackWalker.getInstance().walk(s ->
       s.limit(10).collect(Collectors.toList()));
      
    0 讨论(0)
  • 2020-12-04 08:21

    You can get a stack trace like this:

    Throwable t = new Throwable();
    t.printStackTrace();
    

    If you want to access the frame, you can use t.getStackTrace() to get an array of stack frames.

    Be aware that this stacktrace (just like any other) may be missing some frames if the hotspot compiler has been busy optimizing things.

    0 讨论(0)
  • 2020-12-04 08:22

    You can also send a signal to the JVM to execute Thread.getAllStackTraces() on a running Java process by sending a QUIT signal to the process.

    On Unix/Linux use:

    kill -QUIT process_id, where process_id is the process number of your Java program.

    On Windows, you can press Ctrl-Break in the application, although you usually won't see this unless you're running a console process.

    JDK6 introduced another option, the jstack command, which will display the stack from any running JDK6 process on your computer:

    jstack [-l] <pid>

    These options are very useful for applications which are running in a production environment and cannot be modified easily. They're especially useful for diagnosing runtime deadlocks or performance problems.

    http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/ http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html

    0 讨论(0)
提交回复
热议问题