Search code examples
javastack-overflow

Unable to trace the source of a stack overflow error


I have a Java application that is working as a service. After several days running I get a stack overflow error. The problem is that the stack frame in my source where the error is being originated is not in the error reported by printStackTrace function. I have no idea about how to find where the problem is.

This is the result of printStackTrace:

java.lang.StackOverflowError
    at java.util.LinkedList.listIterator(LinkedList.java:684)
    at java.util.SubList$1.<init>(AbstractList.java:700)
    at java.util.SubList.listIterator(AbstractList.java:699)
    at java.util.SubList$1.<init>(AbstractList.java:700)
    at java.util.SubList.listIterator(AbstractList.java:699)
    at java.util.SubList$1.<init>(AbstractList.java:700)
    at java.util.SubList.listIterator(AbstractList.java:699)
        ... (this is repeated hundreds of times)
    at java.util.SubList.listIterator(AbstractList.java:699)
    at java.util.SubList$1.<init>(AbstractList.java:700)
    at java.util.SubList.listIterator(AbstractList.java:699)
    at java.util.SubList$1.<init>(AbstractList.java:700)

Solution

  • Your problem can be reproduced as follows:

    List<String> l = ...;
    
    for (int i = 0; i < 2800; i++) {
        l = l.subList(...);
    }
    l.listIterator(...);
    

    So, pay attention on all invocations of subList() and make sure they don't form a long chain of sublists as above.

    Such a chain is a recursive structure (each sublist keeps a reference to its parent list), and calling listIterator() on a very long chain causes a very deep recursion which causes stack overflow.