Preston
Preston

Reputation: 3271

ConcurrentModificationException thrown on iterator.remove

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();
        }
}

Upvotes: 1

Views: 719

Answers (2)

user802421
user802421

Reputation: 7505

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.

Upvotes: 2

Daniel
Daniel

Reputation: 28084

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.

Upvotes: 1

Related Questions