Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Sublist throwing StackOverFlowError

We are getting occasional StackOverFlowError errors in production related to doing a SubList operation. Has anyone seen something like this before and know what could cause it?

This is the code that gets called that triggers the error:

  FacesContext context = FacesContext.getCurrentInstance();
    String newViewID = context.getViewRoot().getViewId();

    if (newViewID != null) {
     if (breadCrumbs.contains(newViewID)) {
      // Trims the list upon going back to allow for multiple back button requests.  
      // This is lightweight and not intended for a complex circular navigation.
      breadCrumbs = breadCrumbs.subList(0, breadCrumbs.indexOf(newViewID) + 1);
     } else {
      breadCrumbs.add(newViewID);
     }
    }

The result :

Caused By: java.lang.StackOverflowError
 at java.util.SubList$1.<init>(AbstractList.java:688)
 at java.util.SubList.listIterator(AbstractList.java:687)
 at java.util.SubList$1.<init>(AbstractList.java:688)
 at java.util.SubList.listIterator(AbstractList.java:687)
 ...
like image 763
BestPractices Avatar asked Sep 24 '10 19:09

BestPractices


2 Answers

The subList() method returns a view backed by the original list.

According to the javadoc:

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

You are making structural changes to the list, so all bets are off -- anything can happen, including infinite recursion, which is what appears to be happening.

like image 98
Jim Garrison Avatar answered Oct 15 '22 05:10

Jim Garrison


I had the exact same problem using both LinkedList standard library and fastutil objectarraylist (fastutil are a fast and efficient memory implementation of Java collection framework).

Using

window = window.subList(index+1, window.size());

caused stackoverflow error. I replaced with

window = new LinkedList<>( window.subList(index+1, window.size()) );

and everything worked fine.

Hopes it can help

like image 28
besil Avatar answered Oct 15 '22 05:10

besil