Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JDK 9: An Introduction to StackWalker

DZone's Guide to

JDK 9: An Introduction to StackWalker

StackWalker is an API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces.

· Java Zone
Free Resource

Make it happen: rapid app development on Kubernetes as a managed service.

StackWalker has been introduced in JDK9 as JEP-259. The concepts in this article are taken from 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. Benefits of using StackWalker over Thread::getStackTrace() (prior to JDK9), which are missing in prior releases, are:

  • Filter / assert / skip certain classes.

  • Get the instance of declaring the class itself.

  • Get either short stack trace or complete stack trace, instead of pulling the complete stack trace itself.

The complete code snippet has been put at the end of the article. Let's walk through each section:

Get All Stack Trace Information

Print all stack frame info.

stackFrame.getDeclaringClass()
  // Will give instance of declaring class
List<StackFrame> stack =
  StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) -> s.collect(Collectors.toList()));
System.out.println("All frames : \n" + stack.toString());
//output: 

All frames :
[StackWalkerExample$StackWalker4.stackWalk4(StackWalkerExample.java:46), 
 StackWalkerExample$StackWalker3.stackWalk3(StackWalkerExample.java:39), 
 StackWalkerExample$StackWalker2.stackWalk2(StackWalkerExample.java:33), 
 StackWalkerExample$StackWalker1.stackWalk1(StackWalkerExample.java:27), 
 StackWalkerExample.stackWalk(StackWalkerExample.java:13), 
 StackWalkerExample.main(StackWalkerExample.java:22)]


Filter for Certain Classes

// Filter for interesting classes
final List<Class> interestingClasses = new ArrayList<>();
interestingClasses.add(StackWalker3.class);
Optional<StackFrame> framesWithInterestingClass = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) ->
s.filter(f -> interestingClasses.contains(f.getDeclaringClass())).findFirst()
);

System.out.println("Frame with interseting class : \n"+framesWithInterestingClass.toString());
//output:
rame with interseting class :
Optional[StackWalkerExample$StackWalker3.stackWalk3(StackWalkerExample.java:39)]


Skip Classes in the Stack Frame

Trim the stack frame by skipping a few classes. Using this, we can consider short stack frames:

// Frames with skip
List<StackFrame> framesAfterSkip = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) ->
s.skip(2).collect(Collectors.toList()));

System.out.println("Frames after skip : \n"+framesAfterSkip.toString());


//Output:

Frames after skip :
[StackWalkerExample$StackWalker2.stackWalk2(StackWalkerExample.java:33), 
 StackWalkerExample$StackWalker1.stackWalk1(StackWalkerExample.java:27), 
 StackWalkerExample.stackWalk(StackWalkerExample.java:13), 
 StackWalkerExample.main(StackWalkerExample.java:22)]

// It does not have StackWalker3& StackWalker4, the first two in the list


Complete Code

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.lang.StackWalker.*;

/**
 * Created by vkotari on 12/18/2016.
 */
public class StackWalkerExample {

  private class StackWalker4{
        public void stackWalk4(){
            List<StackFrame> stack =
                    StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) -> s.collect(Collectors.toList()));
            System.out.println("All frames : \n" + stack.toString());

            for(StackFrame stackFrame : stack){
                System.out.println(stackFrame.getDeclaringClass().toString());
            }

            // Filter for interesting classes
            final List<Class> interestingClasses = new ArrayList<>();
            interestingClasses.add(StackWalker3.class);
            Optional<StackFrame> framesWithInterestingClass = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) ->

                s.filter(f -> interestingClasses.contains(f.getDeclaringClass())).findFirst()
            );

            System.out.println("Frame with interseting class : \n"+framesWithInterestingClass.toString());

            // Frames with skip
            List<StackFrame> framesAfterSkip = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) ->
                    s.skip(2).collect(Collectors.toList())
            );

            System.out.println("Frames after skip : \n"+framesAfterSkip.toString());


        }
    }
    public void stackWalk(){
        new StackWalker1().stackWalk1();
    }

    public void print(){
        System.out.println("Hello World.");
    }

    public static void main(String args[]){
        System.out.println("StackWalkerExample...");
        new StackWalkerExample().stackWalk();
    }

    private class StackWalker1{
        public void stackWalk1(){
            new StackWalker2().stackWalk2();
        }
    }

    private class StackWalker2{
        public void stackWalk2(){
            new StackWalker3().stackWalk3();
        }
    }

    private class StackWalker3{
        public void stackWalk3(){
            new StackWalker4().stackWalk4();
        }
    }
}


Tutorial: WordPress as distributed microservices on Kubernetes.

Topics:
java ,jdk 9 ,stackwalker ,stack trace

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}