Thursday, January 13, 2011

java.util.ConcurrentModificationException

I get this while iterating on a collection (a regular java.lang.Vector) and at the same time changing it:

for (PreactivationCallbackTask task : tasks) {
....
tasks.remove(task); // changing the collection while you iterate is not allowed
}


I get this:

java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)


here the javadoc for java.util.ConcurrentModificationException

The only way out is to change the collection OUTSIDE the for loop.

This post provides an excellent explanation.

1 comment:

Reiner Saddey said...

for (Iterator<PreactivationCallbackTask> i = tasks.iterator(); i.hasNext(); ) {

PreactivationCallbackTask task = i.next();
....
i.remove(); // :-)
}