Determining Current Call Stack (For Diagnostic Purposes)

JavaStack Trace

Java Problem Overview


For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when something goes wrong later I can find out who originally triggered the state transition.

Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly:

StackTraceElement[] cause;
try {
  throw new Exception();
} catch (Exception e) {
  cause = e.getStackTrace();
}

Does somebody know of a better way to accomplish this?

Java Solutions


Solution 1 - Java

I think you can get the same thing with:

StackTraceElement[] cause = Thread.currentThread().getStackTrace();

Solution 2 - Java

Well, you can improve it slightly by not actually throwing the exception.

Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] cause = ex.getStackTrace();

Actually, I just checked: the constructor calls fillInStackTrace() already. So you can simplify it to:

StackTraceElement[] cause = new Exception().getStackTrace();

This is actually what Thread.getStackTrace() does if it's called on the current thread, so you might prefer using it instead.

Solution 3 - Java

If you want it as a String and use Apache Commons:

org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())

Solution 4 - Java

There's a new option since JDK 9: StackWalker

It isn't as expensive as Thread.currentThread().getStackTrace().

see also https://stackoverflow.com/questions/2347828/how-expensive-is-thread-getstacktrace

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThilo-Alexander GinkelView Question on Stackoverflow
Solution 1 - Javabruno condeView Answer on Stackoverflow
Solution 2 - JavaMichael MyersView Answer on Stackoverflow
Solution 3 - JavaEdward AndersonView Answer on Stackoverflow
Solution 4 - JavanyxView Answer on Stackoverflow