Alex Rivera | Logout

How to get full stack of StackOverflowError

Asked 2011-03-02T09:50:09.717
40

When observing a StackOverflowError how to retrieve the full call stack?

Consider this simple example:

public class Overflow {

    public Overflow() {
        new Overflow();
    }
    public static void a() {
        new Overflow();
    }
    public static void main(String[] argv) {
        a();
    }
}

Now the error reported is:

Exception in thread "main" java.lang.StackOverflowError
    at Overflow.<init>(Overflow.java:11)
    [last line repeated many times]

But I can't see the main and a method in the stack trace. My guess is this is because of overflow, the newest entry on the stack replaces the oldest one (?).

Now, how to get the a and main stack entries in the output?

The background is I get the a StackOverflowError (but that's not an infinite recursion, because it doesn't happen when increasing stack size) and it's hard to spot the problem in the code. I only get the multiple lines from java.util.regex.Pattern but not the information what code called that. The application is too complicated to set a breakpoint on each call to Patterns.

Edit
Report

1 Answer

4

As far as I know, it's not possible to get the full stack trace (however, I don't really know why).

However, what you could do to track down the problem, is to manually check for the stack depth in your affected code like this:

StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (trace.length > SOME_VALUE) {
  // trigger some diagnostic action, print a stack trace or have a breakpoint here
}

SOME_VALUE would need to be found by experimentation (high enough to not be triggered in "good" situations and low enough to not be unreachable). Of course this would slow down your code and should only be used for debugging the problem.

Update: I seem to have missed that the problem occurs in Pattern, which complicates matters. However, you could use a conditional method breakpoint at one of the Pattern methods in the stack trace with a condition like this (the actual value might need tweaking):

Thread.currentThread().getStackTrace().length > 300

This way you can find your own code at the bottom of the stack when you hit the breakpoint.

answered 2011-03-02T09:55:13.847

Your Answer