What is ConcurrentModificationException and why is it useful

ConcurrentModificationException is thrown by methods when they discover concurrent modification of object which such modifications are not permitted.

So if the collection is modified structurally (add or delete element or change size of backing array) then this exception is thrown.

Generally when one thread is iterating over the collection & another thread modify the collection structurally then this exception is thrown. The iterators that do this are called fait-fast iterators, as they fail quickly and cleanly rather than risking non deterministic behavior at undetermined time in future.

Also, there is one more important thing about this exception. It is not always that different thread will only modify the collection structurally. If we are using iterator to traverse the collection and use remove method of collection rather than of iterator’s remove() method then also this exception is thrown.

Note that fail-fast behavior is on best effort basis. It does not guarantee that collection was not modified. Never assume while writing code that ConcurrentModificationException will handle the structural modification.

Below program throws ConcurrentModificationException.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Iterator<Integer> iterator = numbers.iterator();
while(iterator.hasNext()) {
    iterator.next();
    numbers.remove(2);
}

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)

In this article, we saw that ConcurrentModificationException can be thrown when the structure of List is modified either in multithreaded environment or by using remove(int index) method of List interface rather than Iterator’s remove() method.

Leave a Reply

Your email address will not be published. Required fields are marked *