StackWalker in Java9

Reading Time: 2 minutes

StackWalker was introduced in JDK9 as Stack Walking API or JEP-259StackWalker 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 getStackTrace() method.

Stack-1

The issue with this approach were :

  1. 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.
  2. At times, it skips some of data, as shown by the characters, “…” in the image displayed above.
  3. 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 :

StackWalker.getInstance()
  1. 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 :
    Stack-2
  2. No Skipping of data : We can get the list of all the stack frames without any missing of data:
    Stack-3
  3. 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 :
    Stack-Trace-5

Conclusion : All the issues associated with stack frames until java8, were now easily tackle by java9.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading