How to get the stack trace of current thread in Java

This tutorial demonstrates how to dump stack track of the current thread in Java, this is very useful troubleshoot or debug skill to identify the states of current running thread.

Use Thread.currentThread().getStackTrace() to retrieve an array of StackTraceElements that represent the current stack trace.

This is the example code:

TestDumpThread.java
public class TestDumpThread {
        //Dump the current thread stack trace.
	public static void dumpCurrentStackTrace() {
		StackTraceElement[] stes = Thread.currentThread().getStackTrace();
		for (StackTraceElement element : stes) {
			System.out.println(element);
		}
	}

	public static void main(String[] args) {
		dumpCurrentStackTrace();
	}
}

I executed this program and the output was:

java.lang.Thread.getStackTrace(Unknown Source)
TestDumpThread.dumpCurrentStackTrace(TestDumpThread.java:3)
TestDumpThread.main(TestDumpThread.java:10)
Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

*

code

  1. Michael Vorburger

    So according to http://stackoverflow.com/questions/2347828/how-expensive-is-thread-getstacktrace and https://bugs.openjdk.java.net/browse/JDK-6375302 its (much) faster to use new Throwable().getStackTrace() than the Thread.currentThread().getStackTrace(); proposed here.

    Reply