ConcurrentModificationException

ConcurrentModificationException

As the name indicates, this exception is thrown when two objects are modifying a DS (like Vector or ArrayList) concurrently (at the same time when an operation, like iteration, is going on).

Observe, the following code.

ConcurrentModificationException

Observe, in the while loop, both ListIterator (with it1) and ArrayList (with al1) are adding the elements to the ArrayList concurrently while iteration is going on. This is not allowed.

Fail-Fast

Observe the following code. Even it is an exception.

The iterators of Iterator and ListIterator are fail-fast. While the iteration is going on, the programmer cannot make structural changes (like addition, removal or replacing etc.) on the ArrayList object that returned the ListIterator object. If happens, JVM throws ConcurrentModificationException due to non-deterministic behavior. But while iteration is going on, Iterator or ListIterator object can do the changes in the ArrayList. That is, following works fine.

But the Enumeration object returned by the Vector is not fail-fast.

To be more precise, even the following code throws ConcurrentModificationException.

When once ListIterator object is created, operations on ArrayList object al1 cannot be done. The above code also throws ConcurrentModificationException.

3 thoughts on “ConcurrentModificationException

Leave a Reply

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