ConcurrentModificationException in a single thread

Today I came across a ConcurrentModificationException being thrown when no concurrent work was taking place. I learned (after a bit of hair tearing) that when you are looping over a list and you decide to remove something from it you will get this error.

for(Node n : nodes){
    //do some stuff
    nodes.remove(n);//This will throw the error
}

It makes perfect sense if you think about it. You are stepping over a list, no doubt under the hood somewhere a counter is being used. When you remove a element from a list, all the other elements are shuffled down so now your iterator is going to miss an element and shoot off the end of the list, so instead of that it fails fast and throws an exception. However, more importantly than why it happens, how can we stop it happening? Well we use a list iterator instead.

ListIterator<Node> i = nodes.listIterator();
while(li.hasNext()){
    Node n = i.next;
    li.remove(); //No error if you remove the element through the iterator
}


About this entry