Java 9 Stack Walking API

What is the Stack Walking API

The Java 9 Stack walking API provides an efficient way to walk the jvm stack. The existing methods Thread::getStackTrace() and Throwable::getStackTrace return an array of all stack frames and they do that by grabbing all the frames in the stack. This is performance intensive. The implementation is also allowed to skip a few frames in order to speed up the process. The Stack Walking API allows lazily grabbing frames and also filtering frames based on criteria. The user can choose to walk only a few frames until her criterion is matched or walk the whole frame.

The stack elements are reported in order, starting from the topmost frame. The walk method gives a Stream of StackFrames.

It is possible to pass options to the frame in order to return specific information.

Examples of using the Stack Walking API.

Let’s look at an example of the stack walking API.

Example of StackWalking API


public class ThreadStackWalker {

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new ClassA());

		Thread t2 = new Thread(new ClassB());


class ClassA implements Runnable {
	public void run() {
		StackWalker.getInstance().walk(s -> s.peek(System.out::println).count());

class ClassB implements Runnable {
	public void run() {
		StackWalker.getInstance().walk(s -> s
				.filter(a -> a

In the example above we create two classes ClassA and ClassB that implement Runnable. We create an instance of both threads and start them. For ClassA we walk the stack and print all the frame classes. For ClassB we walk the stack and filter out the frames so that it contains classes that have ‘java9’ in their fully qualified name.

Stack Walking API Creation Options

The StackWalker class takes in 3 different types of options.

  1. StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE) – This allows the StackWalker to support the StackFrame.getDeclaringClass() and StackFrame.getCallerClass() method
  2. StackWalker.getInstance(Option.SHOW_REFLECT_FRAMES) – The reflection frames are hidden by default. This option allows showing the hidden frames.
  3. StackWalker.getInstance(Option.SHOW_HIDDEN_FRAMES) – In addition to the reflection frames some jvm implementation hides the implementation specific frames. This option shows the implementation specific frames.

This completes our discussion on the StackWalking API. In the next article, we look at the project coin changes, specifically the private interface methods.

Leave a Comment