iterator.next() 中的 ConcurrentModificationException
ConcurrentModificationException in iterator.next()
我在后台线程中有下一个代码
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();
}
}
}
当我 运行 在主线程中将 ConcurrentModificationException 放入 iterator.next() 时。
为什么会这样?我使用线程安全集合并通过迭代器删除项目。仅此线程中使用的集合。
同步集合的线程安全仅适用于一个方法调用。在方法调用之间,锁被释放,另一个线程可以锁定集合。如果你执行两个操作,任何事情都可能同时发生,除非你自己锁定它。例如
// 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);
}
与迭代同步集合类似,您必须持有锁,否则在迭代器的方法调用之间可能发生任何事情。
synchronized (mAction) {
for(Iterator<IStartAction> iter = mActions.iterator(); iter.hashNext();) {
IStartAction action = iter.next();
if (!action.isApplicable()) {
iter.remove();
}
}
}
我在后台线程中有下一个代码
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();
}
}
}
当我 运行 在主线程中将 ConcurrentModificationException 放入 iterator.next() 时。 为什么会这样?我使用线程安全集合并通过迭代器删除项目。仅此线程中使用的集合。
同步集合的线程安全仅适用于一个方法调用。在方法调用之间,锁被释放,另一个线程可以锁定集合。如果你执行两个操作,任何事情都可能同时发生,除非你自己锁定它。例如
// 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);
}
与迭代同步集合类似,您必须持有锁,否则在迭代器的方法调用之间可能发生任何事情。
synchronized (mAction) {
for(Iterator<IStartAction> iter = mActions.iterator(); iter.hashNext();) {
IStartAction action = iter.next();
if (!action.isApplicable()) {
iter.remove();
}
}
}