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

JavaDebuggingExceptionLoggingStack Trace

Java Problem Overview


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() but without actually throwing an exception?

My goal is to, in any given method, dump a stack to see who the method caller is.

Java Solutions


Solution 1 - Java

Yes, simply use

Thread.dumpStack()

Solution 2 - Java

You can also try Thread.getAllStackTraces() to get a map of stack traces for all the threads that are alive.​​​​​​

Solution 3 - Java

If you want the trace for just the current thread (rather than all the threads in the system, as Ram's suggestion does), do:

Thread.currentThread().getStackTrace()

To find the caller, do:

private String getCallingMethodName() {
    StackTraceElement callingFrame = Thread.currentThread().getStackTrace()[4];
    return callingFrame.getMethodName();
}

And call that method from within the method that needs to know who its caller is. However, a word of warning: the index of the calling frame within the list could vary according to the JVM! It all depends on how many layers of calls there are within getStackTrace before you hit the point where the trace is generated. A more robust solution would be to get the trace, and iterate over it looking for the frame for getCallingMethodName, then take two steps further up to find the true caller.

Solution 4 - Java

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.

Solution 5 - Java

Notice that Thread.dumpStack() actually throws an exception:

new Exception("Stack trace").printStackTrace();

Solution 6 - Java

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. > > ... > > 2. To snapshot the top 10 stack frames of the current thread, > > List stack = StackWalker.getInstance().walk(s -> s.limit(10).collect(Collectors.toList()));

Solution 7 - Java

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

Solution 8 - Java

If you need capture output

StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();

Solution 9 - Java

The answer by Rob Di Marco is by far the best if you are happy to output to stderr.

If you want to capture to a String, with new lines as per a normal trace, you could do this:

Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );

Solution 10 - Java

HPROF Java Profiler

You don't even have to do this in the code. You can attach the Java HPROF to your process and at any point hit Control-\ to output heap dump, running threads, etc . . . without mucking up your application code. This is a bit outdated, Java 6 comes with the GUI jconsole, but I still find HPROF to be very useful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncorgrathView Question on Stackoverflow
Solution 1 - JavaRob Di MarcoView Answer on Stackoverflow
Solution 2 - JavaPrabhu RView Answer on Stackoverflow
Solution 3 - JavaTom AndersonView Answer on Stackoverflow
Solution 4 - JavaGerco DriesView Answer on Stackoverflow
Solution 5 - JavaAriel TView Answer on Stackoverflow
Solution 6 - JavamkobitView Answer on Stackoverflow
Solution 7 - JavaAndrew NewdigateView Answer on Stackoverflow
Solution 8 - JavaRicardo Jl RufinoView Answer on Stackoverflow
Solution 9 - Javamike rodentView Answer on Stackoverflow
Solution 10 - JavaGandalfView Answer on Stackoverflow