开发者

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 = 开发者_如何学Citer.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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜