Search code examples
javaarraylistcollectionsconcurrentmodification

When will be concurrent modification exception will be thrown and how iterator remove method will work?


According to the javadocs,conncurrent modification exception will be thrown when we will try to structurally modify the collection while iterating over it.Only iterator remove method will not throw concurrent modification exception.

I have analyzed following cases where concurrent modification exception will not be thrown:

List<Integer> var=new ArrayList<Integer>();
var.add(3);
var.add(2);
var.add(5);

1st case:

for(int i = 0; i<var.size(); i++){
    System.out.println(var.get(i));
    var.remove(i);
}

2nd Case:

for(Integer i:var){
    System.out.println(i);
    if(i==2){
        var.remove("5");
    }
}

1)Can anyone please explain how these cases are not throwing Conncurrent Modification Exception? 2)Can anyone please tell how iterator.remove internally works?


Solution

  • According to the Javadoc of ArrayList:

    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

    So, the conditions under which a CME will be thrown are:

    • There must be an iterator (or a list iterator)
    • You must perform a structural modification of the list not via the iterator (i.e. add or remove an element)

    And, perhaps not quite so obviously:

    • After the structural modification, you must call a method on an iterator created before the structural modification.

    i.e. the iterator doesn't attempt to detect the CME until you call next() or remove() on it.