Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Expensive is Thread.getStackTrace()?

Tags:

java

logging

In a logging system, every log output is done by a helper class with a method such as this one

public void debug(String message) {
    Logger logger = Logger.getLogger(getCallingClass());
    logger.debug(message);
}
...
public Class getCallingClass() {
/*
Calls Thread.getStackTrace() and back traces until the class on the stack trace 
!= this.getClass(). 
*/
    return classFound;
}

How expensive is this to run and could it have significant performance hits?

like image 438
Jaime Garcia Avatar asked Feb 27 '10 15:02

Jaime Garcia


1 Answers

Now with JDK 9 & 10, you can use StackWalker, which is not an expensive call.

private void invoke006() {
        var stack = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES).walk((s) -> s.collect(Collectors.toList()));
        stack.forEach(stackFrame -> {
            if (stackFrame.getMethodName().equals("masterInvoker")) {
                System.err.println("master called !!");
                System.err.println(StackWalker.getInstance().walk((s) -> s.collect(Collectors.toList())).get(0).getMethodName() + ", line: " + StackWalker.getInstance().walk((s) -> s.collect(Collectors.toList())).get(0).getLineNumber());
            }
        });
    }
like image 155
user3892260 Avatar answered Oct 26 '22 21:10

user3892260