VOOZH about

URL: https://javarevisited.blogspot.com/2013/04/how-to-get-current-stack-trace-in-java-thread.html

โ‡ฑ How to Get & Print current Thread stack trace in Java - Debugging Tutorial Example


Friday, September 15, 2023

How to Get & Print current Thread stack trace in Java - Debugging Tutorial Example

The stack trace is very useful while debugging or troubleshooting any issue in Java. Thankfully Java provides a couple of ways to get a current stack trace of a Thread in Java, which can be really handy in debugging. When I was new to Java programming and didnโ€™t know how to remote debug a Java application, I used to put debug code as patch release, which uses classpath to pick debug code for printing stack trace and shows how a particular method is get called and that sometimes provide a vital clue on missing or incorrect argument.

Now, When I have a couple of Java debugging tips on my sleeve, I still think knowledge of how to get a current stack trace in Java for any Thread, or simply print the stack trace from any point in code worth knowing. 

For those who are not very familiar with a stack trace and wondering what is the stack trace in Java, here is a quick revision. The thread executes code in Java, they call methods, and when they call, they keep them in their stack memory. 

You can print that stack trace to find out, from where a particular method is get called in the execution flow. This is especially useful if you are using a lot of open-source libraries, and donโ€™t have control over all the code. 

One of the most familiar faces of stack trace in Java is printing stack trace using Exception.printStackTrace(), when an Exception or Error is thrown in Java. In this Java tutorial, we will look at a couple of ways to print and get the current stack trace of a Thread in Java.



One of the easiest ways of the printing stack traces of the current thread in Java is by using the dumpStack()method from java.lang.Thread class. This method prints a stack trace of thread on which it gets called. 

You can use Thread.currentThread() method to get the reference of current thread before calling this method. 

Another way to print stack trace is using the printStackTrace() method of the Throwable class. Just use new Throwable().printStackTrace() method and it will print complete stack trace from where a method is called, into the console. 


Main difference between using dumpStack() and printStackTrace() is first entry in Stack, In case of dumpStack() first entry is always java.lang.Thread.dumpStack(), while in the latter case it's the method from where you printed stack trace. 

If you don't want to print stack trace and rather want it in the Java program, you can use getStackTrace() method from the Thread class. This method returns an array of StackTraceElement

In the following Java program, we will see examples of all three approaches to get a stack trace of the current thread in Java.


import java.util.logging.Logger;

/**
 * Java program to demonstrate how to print and get stack trace for current
 * thread in Java. Stack trace are useful information while debugging or
 * troubleshooting any issue.
 *
 * @author Javin Paul
 */
public class StackTraceExample {
 private static final Logger logger = Logger.getLogger(StringReplace.class.getName());
 
 public static void main(String args[]) {
 
 //calling a method to print stack trace further down
 first();
 } 
 
 public static void first(){
 second();
 }

 private static void second() {
 third();
 }

 private static void third() {
 
 //If you want to print stack trace on console than use dumpStack() method
 System.err.println("Stack trace of current thread using dumpStack() method");
 Thread.currentThread().dumpStack();
 
 //This is another way to print stack trace from current method
 System.err.println("Printing stack trace using printStackTrace() 
 method of Throwable ");
 new Throwable().printStackTrace();
 
 //If you want stack trace as StackTraceElement in program itself than
 //use getStackTrace() method of Thread class
 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
 
 //Once you get StackTraceElement you can also print it to console
 System.err.println("displaying Stack trace from StackTraceElement in Java");
 for(StackTraceElement st : stackTrace){
 // System.err.println(st);
 }
 
 }
 
}

Stack trace of current thread using dumpStack() method
java.lang.Exception: Stack trace
 at java.lang.Thread.dumpStack(Thread.java:1249)
 at test.StringReplace.third(StringReplace.java:38)
 at test.StringReplace.second(StringReplace.java:31)
 at test.StringReplace.first(StringReplace.java:27)
 at test.StringReplace.main(StringReplace.java:23)
Printing stack trace using printStackTrace() method of Throwable
java.lang.Throwable
 at test.StringReplace.third(StringReplace.java:42)
 at test.StringReplace.second(StringReplace.java:31)
 at test.StringReplace.first(StringReplace.java:27)
 at test.StringReplace.main(StringReplace.java:23)
displaying Stack trace from StackTraceElement in Java


That's all on How to get current stack trace in Java. By using the above methods you can get a stack trace from current thread or any other Thread. If you are also interested on taking thread dump, than you can use kill -3 pid in UNIX environment and ctrl+break in the Windows environment. 

This will instruct JVM to print stack trace of all threads in the console.

And lastly,  let me know if you have been asked this question before? or what is your favorite Java multithreading interview question?

4 comments :

Borislav Kirilov said...

I see you are declaring logger, but not using it in the example. I say that, because I'm trying to solve the same problem - to print the stack trace - but want to print it in the logger ... The thing is that the method Thread.currentThread().getStackTrace() is available since Java 1.5, but I'm using Java 1.4. Any idea how to print the stack trace in the logger with Java 1.4?

April 8, 2013 at 7:03โ€ฏAM ๐Ÿ‘ Image
dalewking said...

The RoboGuice framework includes a logger class that uses this technique to find the class that is making the logging call. It is a logger that requires no configuration (i.e. you don't have to pass a class or string tag to it to tell it which logger it is). All you do is make static method calls.

See the source here: https://github.com/roboguice/roboguice/blob/master/roboguice/src/main/java/roboguice/util/Ln.java

April 22, 2013 at 7:05โ€ฏAM ๐Ÿ‘ Image
SARAL SAXENA said...

@Javin perfect article ..just want to add what I have added ..

I have a utility method that returns a string with the stacktrace:

static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}

And just logit like...

...
catch (FileNotFoundException e) {
logger.config(getStackTrace(e));
}

March 29, 2014 at 9:10โ€ฏAM ๐Ÿ‘ Image
Unknown said...

Pls solved error application

December 16, 2018 at 11:19โ€ฏAM ๐Ÿ‘ Image

Post a Comment

Search This Blog

Preparing for Java and Spring Boot Interview?

Get New Blog Posts on Your Email

Followers

Categories

Blog Archive