Visitor :

May 4, 2009

ConcurrentModificationException in java collection object

When you meet java.util.ConcurrentModificationException, you may suspect your code about modifying collection for iterating.


Below code occur java.util.ConcurrentModificationException, because java code try to change arraylist for iterating.


// copy is arraylist.
for (MBeanConnection notiConnection : copy) {
MetaConnectionData data = notiConnection.getMetaConnectionData();
int index = Collections.binarySearch(newConnList, data, notiComparator);
if (index >= 0) {
notiConnection.remove(index);
removedIndexList.add(index);
newConnList.remove(data);
}
}

So, java code have to change not to modify for iterating, or you have to clone the collections to avoid modification using clone() method.


List removedIndexList = new LinkedList();
for (MBeanConnection notiConnection : copy) {
MetaConnectionData data = notiConnection.getMetaConnectionData();
int index = Collections.binarySearch(newConnList, data, notiComparator);
if (index >= 0) {
notiConnection.remove(index);
removedIndexList.add(index);
newConnList.remove(data);
}
}

// To avoid ConncurrentModification Error
for (Integer i : removedIndexList) {
copy.remove(i.intValue());
}

No comments:

Post a Comment