Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the thread getStackTrace() function in Java?

Fouzia Bashir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The getStackTrace() method

The getStackTrace() method is used to return the array regarding stack trace elements. These elements represent the stack dump related to the thread.

How does getStackTrace() work?

  • If this thread has been dismissed or has not started, then the method will return an array of zero-length.

  • If a non-zero array is returned, then the first element of that array shows the top of the stack.

  • getStackTrace() is the most recent method of invocation in the series. The bottom of the stack is represented by the last element of an array.

  • getStackTrace() is the least recent method of invocation in the series.

Syntax


StackTraceElement[ ] getStackTrace( )

Parameters

getStackTrace does not take any parameters.

Return value

The function returns the array regarding StackTraceElement, and every element shows a single stack frame.

SecurityException

The checkPermission method occurs when a security manager exists. This method does not permit getting the stack trace of the thread.

Code

The code below demonstrates how to use the getStackTrace() function.

// Load library
import java.lang.Thread;
// Main class
public class Test_thread{
// main method
public static void main(String[] args) {
function();
}
public static void function() {
new Test_thread().function2();
}
public void function2() {
System.out.println(Thread.currentThread().getStackTrace()[3].getClassName());
}
}

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring