Video in progress
What is StackWalker, and how is it better than Thread.getStackTrace() or new Throwable().getStackTrace()?
StackWalker (Java 9) gives the stack lazily, as a stream: only the frames you need are read, and a full StackTraceElement[] array isn't created. It is much cheaper when you need the caller class or just a frame or two from the stack.
📖 Answer
The old way is to take the whole stack:
StackTraceElement[] st = new Throwable().getStackTrace();
String caller = st[1].getClassName();
The problem: the JVM collects all the frames (100-200 in a Spring application), creates a StackTraceElement for each and fills in the strings. Even if you need one frame, you pay for all of them.
With StackWalker:
private static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Class<?> caller = WALKER.getCallerClass();
// or find the first frame that is "ours"
Optional<String> where = WALKER.walk(frames -> frames
.filter(f -> f.getClassName().startsWith("com.acme"))
.map(f -> f.getClassName() + "#" + f.getMethodName())
.findFirst());
Frames are read as they arrive in the stream, and if it is stopped with findFirst, the rest are not loaded at all.
The options:
RETAIN_CLASS_REFERENCE: to get theClassobject (required forgetCallerClass);SHOW_REFLECT_FRAMES,SHOW_HIDDEN_FRAMES: to show reflection and lambda frames.
Where it is used: logging libraries (which class/line wrote the log, location info in Log4j2), security checks, "who called this" diagnostics.
It is still not cheap: walking the stack on every call on a hot path costs CPU. That is why location info in logs (%L, %M) is often turned off on prod.
Sign up to mark studied questions and save your progress.