When you debug a complex Java code which has some parallel threads running, it is not easy to capture all the breakpoints and sometimes it is really hard to find which path has caused the problem. In such a scenarios, we need to print the method call stack at suspected locations. How can I print the method call stack within Java?
3 Answers
Here is how you print the stack trace from a given location in your source file.
System.out.println("Printing stack trace:");
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement s = elements[i];
System.out.println("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
}
5 Comments
Dawood ibn Kareem
I don't think this gives you any more information than using the debugger in an IDE would give you. Also, it doesn't give you the opportunity to let you see the values of your variables, in the way a debugger would. I can't imagine any circumstance in which this would be useful. It rather looks to me that you've brought a bicycle to the Formula One.
duffymo
Correct, but not very useful.
David Zimmerman
even easier new Throwable().printStacktrace()
Thomas Fischer
To all the people who say that this isn't very useful: The OP said that this is to debug a multi-threading issues ("parallel threads"). Using the debugger, one might not be able to catch a combination of threads in the exact state to cause an issue. So, the combination of how this code and how it is triggered can be very useful. (The debugger has some ability with conditional breakpoints to get close to an exact multi-threading condition, but there are more scenarios to get stack traces based on multiple thread states.)
Gavrilo Adamovic
Also, you can log stacktraces to log files and wait for some edge case to happen before checking the logs, which you definitely can't do in an IDE, so definitely very useful.
Just use below code
System.out.println("Stack trace:");
StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
for (int i = 1; i < stackTraces.length; i++) {
System.out.println(stackTraces[i]);
}
This is definition of toString method of StackTraceElement
public String toString() {
return getClassName() + "." + methodName +
(isNativeMethod() ? "(Native Method)" :
(fileName != null && lineNumber >= 0 ?
"(" + fileName + ":" + lineNumber + ")" :
(fileName != null ? "("+fileName+")" : "(Unknown Source)")));
}
So you can use directly to print StackTraceElement.
1 Comment
nagendra547
Why downvoting?