这是我的课:
public class AComplicatedclass {
private List<Connection> activeConnections;
private Lock lock = new ReentrantLock();
public void printConnections() {
lock.lock();
for(Connection c : activeConnections){ //exception happens here
...prints details about connection
activeConnections.remove(c);
}
lock.unlock();
}
private class MyThread extends TimerTask {
public void run() {
lock.lock();
...can alter activeConnections....
lock.unlock();
}
}
}
正如您所看到的,锁对象应该可以防止由于并发访问该共享数组而导致的问题。然而,当调用 printConnections()
方法时,我在该 for
中得到一个 ConcurrentModificationException
。
怎么会呢?根本没有并发修改!
最佳答案
很可能您在 for 循环内修改了集合。正如 ConcurrentModificationException 上的文档所示州
For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
迭代器抛出异常的原因是它无法再确定下一个要返回哪个元素。
因此,如果您想修改您的集合,您需要切换到类似 CopyOnWriteArrayList 的内容。或使用Iterator明确如
Iterator<Connection> iterator = activeConenctions.iterator();
while(iterator.hasNext()) {
Connection c = iterator.next();
if(/* what ever */) {
iterator.remove();
}
}
关于java - 为什么即使我使用锁也会收到 ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905624/