The ConcurrentModificationException

Have you ever tried to modify a collection on which you are iterating upon? In case you have, you have also probably encountered the evil called the Concurrent Modification Exception. In case you want to get rid of the concurrent modification exception, you will have to understand the cause of its occurrence.

Please never believe in the myth, that only enhanced for loops can cause this exception. The good old iterators do throw the same exception. But, it is also a fact that one cannot escape concurrent modification exception when using enhanced for loop.

Why does it happen? Well it happens due to the fact that AbstractList keeps a count of the structural modifications made to the List. Adding or removing items from a list can be considered to a structural change. Iterator’s next() method also used the modCount which stores the number of times a list has been modified. Thus, when trying to get to get to the next item in the application, this exception is thrown.

Solution to the problem:

1. One of the solution to the problem is to use an array instead of a collection. Which just fails performance wise when one is iterates over a large colleciton.

2. The other solution is to update the list values instead of actually adding or deleting the whole item. This of course cannot be pulled of every time.

3. One simple way is to remove an item from the collection, but only that item, which is the current item in the iteration. (Iterator.remove())

4. Concurrent collections are another possible solution.

5. Synchronous block is another way to go. Just lock the collection.

Just do whatever you want to with the iterator’s next() reference and you should be fine.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: