Search code examples
javaconcurrentmodification

ConcurrentModification Exception on Sorting


I wrote this small program to sort arrays. To my understanding it should print 0,1,2.

However, when I run this program I am getting ConcurrentModificationException

    public class Test {
    public static void main(String[] args) {
    List<Double> l1 = new ArrayList<Double>(Arrays.asList(2., 0., 1.));
    List<Double> l2 = l1.subList(0, 3);
    Collections.sort(l1);
    System.out.println(l2.get(0));
    }
}

I am really not sure about the root cause of this exception.

Can somebody help me understand where I am making mistake ?

Note: This issue is not there on JAVA 7 , It would be great if some one also tell why it is there in JAVA 8 and not in JAVA 7


Solution

  • The API docs of List.subList say:

    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.)

    Sorting would indeed change the list in such a way that iterations in progress would lead to incorrect results. The API docs say that what happens in that case is undefined - in practice this means that a ConcurrentModificationException is thrown (at least, when using Java 8), as your code demonstrates.