Pages

Thursday, October 13, 2011

ConcurrentModificationException in the nutshell


package com.sopovs.moradanen;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConcurrentModificationExceptionTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList(Arrays.asList("first"));
        for (String el : list) {
            list.add("second");
        }
    }
}
Results in


Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at com.sopovs.moradanen.ConcurrentModificationExceptionTest.main(ConcurrentModificationExceptionTest.java:11)


Update: This may look strange, though...

ArrayList<String> list = new ArrayList<String>(Arrays.asList("foo", "bar"));
for (String el : list) {
    //Capacity will not be increased, but iterator will fail...
    list.ensureCapacity(1);
}

No comments:

Post a Comment