这是我的问题:
这段代码抛出一个java.util.ConcurrentModificationException
,因为Vector
listeners
被修改,而Iterator存在
这个数据结构。
java-doc 说这个容器只提供了一个快速失败的迭代器。
是否有可能在 Java 中的 Vector
或 List
等标准容器上获得 Iterator
并为我提供 Iterator
,如果在 Iterator
“存在”期间删除了一个元素,那不会变得无效(不是快速失败)?
我应该具有与 C++ 中的 std::list
相同的行为。即使删除了当前迭代器,迭代器也始终有效。然后将迭代器设置为列表中的下一个元素。
public class ClientHandle {
private final Vector<ClientHandleListener> listeners = new Vector<ClientHandleListener>();
public synchronized void addListener(ClientHandleListener chl) {
listeners.add(chl);
}
public synchronized void removeListener(ClientHandleListener chl) {
listeners.remove(chl);
}
private void fireConnectionClosed() {
final ClientHandle c = this;
final Iterator<ClientHandleListener> it = listeners.iterator();
new Thread(){
@Override
public void run() {
while (it.hasNext()) {
it.next().connectionClosed(c); //FIXME the iterator gets modified
}
};
}.start();
}}
public class ClientHandlePool implements ClientHandleListener, TaskManagerListener {
/*...*/
public synchronized void removeClientHandle(ClientHandle ch) {
//here the listeners Vector from the ClientHandle gets modified
ch.removeListener(this);
ch.removeListener(currentListener);
clientHandles.remove(ch);
}
@Override
public void connectionClosed(ClientHandle ch) {
removeClientHandle(ch);
}
}
最佳答案
据我所知,没有办法将该功能追溯添加到任何默认的 Collection
实现(实际上是 Iterable
)。
但是有些实现通过在迭代时对并发修改做出明确的响应来支持这种行为。
一个例子是 CopyOnWriteList
.
关于java - Java 容器是否提供故障安全迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2358126/