ConcurrentModificationException - How It Works

ConcurrentModificationException is one of the interesting exception which is caused when concurrent updates (add, remove, update) happens to collections.  In this article, I will show an example which throws ConcurrentModificationException without using threading.

If you run this code, you will get ConcurrentModificationException,

Do you see any line which can throw ConcurrentModificationException?

Yes foundListIterator.next() can throw ConcurrentModificationException, because the content of the iterator is modified after the iterator was created.

The Sun's implementation for the next() method checks for the number of times this list has been structurally modified and the value that the iterator believes that the backing List should have. If this expectation is violated, the iterator has detected concurrent modification.

How to avoid such exception?  Create the Iterator only when you need and not in advance.
The modified version of the above code will look like,

To avoid such cases it is better to use for...each instead of iterator().
The better code looks like,