简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM