Search code examples
javalistsortingiterationconcurrentmodification

List iteration throws ConcurrentModificationException in Java 8 when sorting already sorted list


Just in case anyone else has a similar issue, I thought I'd post my issue and solution here.

Basically, I had code that was working fine under Java7, but was consistently throwing a ConcurrentModificationException in Java8. The structure was basically this:

List<FormatData> formats = service.getFormat(type);
for (FormatData f : formats) {
    /* Do stuff here */
}

However, part of the "Do stuff here" part ended up calling the same service.getFormat(type) function and returning the same list. However, that same function looked up the list but also sorted the list. In Java7, since the list was already sorted, it didn't modify it. In Java8, it treats re-sorting a sorted list as having been modified.


Solution

  • My solution was twofold, either one would have worked. First of all, I moved the sorting away from the retrieve function so I wouldn't waste time - instead I moved it to the load function where it should have been in the first place. Secondly, in a lesser used function that returned the same list but sorted differently, I just created a new list, which I then sorted and returned:

    result = new ArrayList(oldList);
    Collections.sort(result, otherComparator);
    

    In addition, before returning on either side, I added this to ensure no more modifications can occur without throwing exceptions:

    result = (result==null) ? null : Collections.unmodifiableList(result);