java - Java 容器是否提供故障安全迭代器

标签 java iterator fail-fast

这是我的问题:

这段代码抛出一个java.util.ConcurrentModificationException,因为Vector listeners被修改,而Iterator存在 这个数据结构。 java-doc 说这个容器只提供了一个快速失败的迭代器。

是否有可能在 Java 中的 VectorList 等标准容器上获得 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/

相关文章:

javascript - 为什么 ES6 中的 Iterator.next() 方法不能直接返回值?

c++ - 显示和保存对象的链接列表

java - 有很多最终字符串,你建议将它们放在java中什么?

使用 USB 证书进行 Java 加密(智能卡)

java - 从 Java 调用 Kotlin — 错误 : package demo does not exist

c++ - 为 boost::iterator_adapter 设置 iterator_bracket_proxy

exception - 如何让Storm因异常而停止?

short-circuiting - Hystrix 配置

c# - 优雅地处理损坏的状态异常

java - 由于递归规则调用,ANTLR3 错误规则具有非 LL(*) 决策