ConcurrentModificationException may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. This exception is encountered more often in case of collections when one thread is iterating over the collection and other tries to modify it.
This article explains how java detects concurrent modifications to a List with the help of an example. The comments provided along with the code are self explanatory so let us go through the example first:
ConcurrentModificationTest.java
package com.technicalmusings.examples.collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* The class explains how concurrent modification is detected in List.
*/
public class ConcurrentModificationTest {
public static void main(String[] args) {
// Instantiating the list sets the modCount field of list to 0
// modCount is a protected integer variable defined in the AbstractList class.
List<Object> myList = new LinkedList<Object>();
myList.add(new Object()); // modCount incremented to 1
myList.add(new Object()); // modCount incremented to 2
myList.add(new Object()); // modCount incremented to 3
// Getting an iterator sets the value of expectedModCount field
// equal to that of the modCount field of list.
Iterator<Object> itr1 = myList.iterator(); //itr1: expectedModCount = 3
Iterator<Object> itr2 = myList.iterator(); //itr2: expectedModCount = 3
// The first Iterator traverses the list once
itr1.next();
// The second iterator traverses and removes the first element
itr2.next();
itr2.remove();
// In the previous step Itr2 modifies the list and sets the
// expectedModCount field to 4. The modCount field of the list
// has also been now incremented to 4
// The first iterator again tries to traverse the list
itr1.next();
// java.util.ConcurrentModificationException is thrown at this stage
// because itr1 finds its expectedModCount (which is still 3) to be not
// matching with the modCount field of the list
}
}
The ConcurrentModificationTest.java class shown above explains how java works behind the scenes to detect concurrent modification and throw the ConcurrentModificationException in case of a List. List has an integer field modCount, which is incremented each time a structural modification is done in the list. Structural modification includes methods like add, remove, clear etc. The Iterator on the other hand uses another integer field, expectedModCount, to take care of concurrent modifications in the list. Iterator expects both the variables modCount and expectedModCount to be the same. In case the list is modified by any other means the modCount and expectedModCount differs and the exception is thrown.