StackWalker was introduced in JDK9 as Stack Walking API or JEP-259. StackWalker gives the snapshot of the stack trace of the current thread at any given point of time and has methods to walk over it. Now, we can easily filter out the information required, sort them and perform almost all the stream operations provided by Java.
Issue with Stack Trace Before Java9
Before Java9, we could obtain a stack trace by creating an instance of
Throwable() and then invoking
The issue with this approach were :
- It gives the snapshot of the entire stack, even when we only needed first or last few frames. Thus, it is costly and impacts the performance.
- At times, it skips some of data, as shown by the characters, “…” in the image displayed above.
- Further, there was direct way to access the actual class instance of the class that declared the method represented by a stack frame.
Resolution with Java9
Let’s have a look at how all these problems were tackled by Java9. Firstly, we will create an instance of StackWalker :
- Application of streams operations on stack frames : Now, we can start walking over it and perform the operations over the stream of StackFrame, traversing from the top of the stack. Thus, the walk API takes a function that maps the given
Stream<StackFrame>to anything we want. In the example shown below, we have extracted out the snapshot of the first three stack frames :
- No Skipping of data : We can get the list of all the stack frames without any missing of data:
- Getting the class instances : In order to get the class instance, we need to retain the class reference and then get the declaring class as shown in the image below :
Conclusion : All the issues associated with stack frames until java8, were now easily tackle by java9.