简体   繁体   English

iterator.next()中的ConcurrentModificationException

[英]ConcurrentModificationException in iterator.next()

I have next code in background thread 我在后台线程中有下一个代码

private List<IStartAction> mActions = Collections.synchronizedList(new ArrayList<IStartAction>()); 

protected void removeNonApplicableActions() {
        Iterator<IStartAction> iterator = mActions.iterator();
        while (iterator.hasNext()) {
            IStartAction action = iterator.next();
            if (!action.isApplicable()) {
                iterator.remove();
            }
        }
    }

When i run this in main thread got ConcurrentModificationException into iterator.next(). 当我在主线程中运行此命令时,将ConcurrentModificationException放入了iterator.next()中。 Why is this happening? 为什么会这样呢? I use thread-safe collection and remove items through iterator. 我使用线程安全的集合并通过迭代器删除项目。 Collection used in only this thread. 仅在此线程中使用集合。

Thread safety for a synchronized collection only applies to one method call. 同步集合的线程安全性仅适用于一个方法调用。 Between method calls the lock is released and another thread can lock the collection. 在方法调用之间,锁定被释放,另一个线程可以锁定该集合。 If you perform two operations, anything could happen in the meantime, unless you lock it your self. 如果执行两次操作,则在此期间可能会发生任何事情,除非您将其锁定为自己。 eg 例如

// to add two elements in a row, you must hold the lock.
synchronized(mAction) {
    mAction.add(x);
    // without holding the lock, anything could happen in between
    mAction.add(y);
}

Similarly to iterate over a synchronized collection, you have to hold the lock, otherwise anything could happen between method calls to the iterator. 与迭代同步集合类似,您必须持有锁,否则在迭代器的方法调用之间可能会发生任何事情。

synchronized (mAction) {
    for(Iterator<IStartAction> iter = mActions.iterator(); iter.hashNext();) {
        IStartAction action = iter.next();
        if (!action.isApplicable()) {
            iter.remove();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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