How to get stack trace using thread in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 has added StackWalker class to provide a standard API for accessing the current thread stack. In the previous java versions, we can use Throwable::getStackTrace, Thread::getStackTrace, and SecurityManager:: GetClassContext provided methods to obtain the thread stack.

Thread.getStackTrace() method will return an array of stack trace elements representing the stack dump of a thread (StackTraceElement[]). The first element of an array represents the top of a stack, it can be the last method invocation in a sequence, and the last element of an array represents the bottom of a stack, it can be the first method invocation in a sequence.

Syntax

public StackTraceElement[] getStackTrace()

Example

import java.lang.StackWalker.Option;

public class GetStackTraceTest {
   public static void main(String args[]) {
      GetStackTraceTest.testPrintCurrnentStackTrace();
      GetStackTraceTest.testShowReflectFrames();
   }
   // get StackTrace using Thread
   public static void testPrintCurrnentStackTrace() {
      StackTraceElement[] stack = Thread.currentThread().getStackTrace();
      for(StackTraceElement element : stack) {
         System.out.println(element);
      }
   }
   // SHOW_REFLECT_FRAMES
   public static void print(StackWalker stackWalker) {
      stackWalker.forEach(stackFrame -> System.out.printf("%6d| %s -> %s %n",
stackFrame.getLineNumber(), stackFrame.getClassName(), stackFrame.getMethodName()));
   }

   public static void testShowReflectFrames() {
      final StackWalker stackWalker = StackWalker.getInstance(Option.SHOW_REFLECT_FRAMES);
      print(stackWalker);
   }
}

Output

java.base/java.lang.Thread.getStackTrace(Thread.java:1654)
GetStackTraceTest.testPrintCurrnentStackTrace(GetStackTraceTest.java:10)
GetStackTraceTest.main(GetStackTraceTest.java:5)
   17| GetStackTraceTest -> print
   25| GetStackTraceTest -> testShowReflectFrames
   6| GetStackTraceTest -> main
raja
Published on 23-Apr-2020 12:19:48
Advertisements