1

I'm getting a ConcurrentModificationException despite using the iterator to perform the remove operation. Any ideas as to why?

for (Iterator<Thread> iter = threads.iterator(); iter.hasNext();) {
        Thread hook = iter.next();
        if(someCondition){
                iter.remove();
        }
}
2
  • 3
    My guess is that another thread is messing with the threads list. Some thread may for instance be appending something on the list?
    – aioobe
    Aug 1, 2011 at 16:03
  • aren't you also modifying at the same time?
    – Sagar V
    Aug 1, 2011 at 16:04

2 Answers 2

2

From JavaDoc Iterator.remove():

Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

It seem that the behavior is depended to the collection. Also as aioobe pointed out. I can reproduce ConcurrentModificationException when I modify the collection somewhere else. Using only Iterator interface, I can only reproduce IllegalStateException.

1

Because you have a modification concurrent to using an Iterator, which is not supported. Either iterate a list clone, or use a CopyOnWriteArrayList.

Or memory what to remove in a new list, and call list.removeAll(whatIWantedToRemove) afterwards.

2
  • 4
    a modification concurrent to using an Iterator Should be ok as long as the modification is done through the iterator as described by the OP.
    – aioobe
    Aug 1, 2011 at 16:02
  • A list clone can suffer from the same problem because to create the clone it iterates the original list. However, I think this might be the safest approach.
    – Preston
    Aug 1, 2011 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.