DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java Stream API: 3 Things Every Developer Should Know About
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Functional Approach To String Manipulation in Java
  • Techniques You Should Know as a Kafka Streams Developer

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Concourse CI/CD Pipeline: Webhook Triggers
  1. DZone
  2. Data Engineering
  3. Databases
  4. Stack-Walking in Java With StackWalker and the Stream API

Stack-Walking in Java With StackWalker and the Stream API

Want to learn more about using the Stack-Walking API in Java? Check out this tutorial on how to use the StackWalker and Stream APIs.

By 
Grzegorz Piwowarek user avatar
Grzegorz Piwowarek
·
Sep. 11, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

One of the coolest — and totally impractical —  features added to Java recently is the Stack-Walking API.

In this short article, we’ll check it out and see how surprisingly easy it is to use.

Stack-Walking Before Java 9

So far, the official solution was to obtain the current thread and call the  getStackTrace() method:

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();


The other smart solution involved included throwing an exception and extracting stack trace information from it. However, it wasn’t possible to manipulate the result; it would just get printed instantly:

new Exception().printStackTrace();


Both solutions suffer from the same problem — they eagerly capture a snapshot of the entire stack and aren’t handy to use.

JEP-259: Stack-Walking API

JEP-259 was supposed to address those problems, and it did. The new API provides a handy way of traversing stack traces lazily using Stream API.

We can create a StackWalker instance as easily as:

StackWalker stack = StackWalker.getInstance();


Additionally, we can provide some initial options:

StackWalker stack = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);


And, if we want to traverse the whole stack, it’s simply a matter of calling the forEach() method:

stack.forEach(System.out::println);


StackWalker.StackFrame

If we look at the Java 1.4’s StackTraceElement, it’s pretty much a DTO containing String information about a declaring class, method name, classloader name, etc.

 StackWalker.StackFrame is a much more type-safe-friendly upgrade that is enriched with methods like:

public Class<?> getDeclaringClass();


public MethodType getMethodType();


And, even:

public StackTraceElement toStackTraceElement();


This is the case if we missed the legacy format.

Example

Let’s put that into action and create a simple call hierarchy:

public static void main(String[] args) {
    foo();
}

private static void foo() {
    bar();
}

private static void bar() {
    java.lang.StackWalker
      .getInstance(java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE)
      .forEach(System.out::println);
}


And, if we run it, the result will look like the following — notice the order of the stack elements:

com.pivovarit.stack.StackWalker.bar(StackWalker.java:16)
com.pivovarit.stack.StackWalker.foo(StackWalker.java:10)
com.pivovarit.stack.StackWalker.main(StackWalker.java:6)


Advanced Features

If we want to leverage laziness or frame filtering, we can use the other dedicated API method called walk() that allows us to use the Stream API to conveniently traverse the stack. While reading this, you probably imagined the walk() method to simply return a Stream instance. Well, this is not the case.

The actual signature is:

public <T> T walk(Function<? super Stream<StackFrame>, ? extends T> function)


And, there’s a good reason for it to be this way — the stack needs to be frozen for it to be traversed, and this happens within the scope of the walk() method call, so it makes sense to utilize the functional-interface-based template method implementation to achieve that.

Even if you try to trick it by returning a Stream instance, it won’t be usable. You can try it yourself if you don't believe me!

Once we know that limitation, we’re only bound by our imagination and the Stream API capabilities. For example, we can gracefully skip some frames and pick the first encountered one:

java.lang.StackWalker
  .getInstance(java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE)
  .walk(s -> s.skip(1).limit(1).collect(Collectors.toList()))
  .forEach(System.out::println);

// result
com.pivovarit.stack.StackWalker.foo(StackWalker.java:12)
API Stream (computing) Java (programming language)

Published at DZone with permission of Grzegorz Piwowarek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java Stream API: 3 Things Every Developer Should Know About
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Functional Approach To String Manipulation in Java
  • Techniques You Should Know as a Kafka Streams Developer

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!