nut*_*rio 1 java iterator fail-fast
这是我的问题:
这段代码抛出一个java.util.ConcurrentModificationException,因为在Vector listeners存在Iterator这个数据结构时会被修改.java-doc说这个容器只提供一个快速失败的迭代器.
如果在"生命" 期间删除了一个元素,是否有可能获得Iterator像Java Vector或ListJava那样的标准容器Iterator,它不会失效(不是快速失败)Iterator?
我应该像std::list在C++中一样具有相同的行为.即使删除了当前的迭代器,迭代器也始终有效.比迭代器设置为列表中的下一个元素.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,没有办法追溯性地将该功能添加到任何默认Collection实现(Iterable事实上).
但是有些实现通过在迭代时对并发修改做出明确定义的响应来支持这种行为.
一个例子是CopyOnWriteList.
| 归档时间: |
|
| 查看次数: |
2756 次 |
| 最近记录: |