Why Java Iterator throws ConcurrentModificationException?

Many times you will be asked this question in the interviews. e.g. how Iterator works in java, how it removes objects from the List? While removing objects from the list, when it may produce ConcurrentModificationException?

1. ConcurrentModificationException

In Java, when we create an Iterator, it counts the modifications applied to the collection. If the Iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass through twice on the same element or skip one element during iteration, so it throws this exception.

2. Matching Modcount

As we know that the ArrayList methods always increase a counter ‘modCount‘ declared as:

protected transient int modCount = 0;

When we create an Iterator/ListIterator on arraylist, this modCount is used to initialize expectedModCount for that Iterator instance.

int expectedModCount = modCount;

Any operation done on ArrayList directly (without using the iterator instance) will increase the modCount.

Iterator‘s all methods perform a check to validate the equality of modCount == expectedModCount – before performing the operation. If they do not match, it simply throws the exception.

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

I hope the above explanation will help you answer this interview question.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial