Skip to content
Advertisement

Why is a ConcurrentModificationException thrown and how to debug it

I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

JavaScript

Advertisement

Answer

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

JavaScript

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

JavaScript

Assuming this iterator supports the remove() operation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement