【问题标题】:Why isn't this code causing a ConcurrentModificationException? [duplicate]为什么这段代码不会导致 ConcurrentModificationException? [复制]
【发布时间】:2013-01-18 09:07:18
【问题描述】:

我正在阅读有关 ConcurrentModificationException 以及如何避免它的信息。找到an article。该文章中的第一个清单具有类似于以下的代码,这显然会导致异常:

List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");

Iterator<String> it = myList.iterator();
while(it.hasNext())
{
    String item = it.next();
    if("February".equals(item))
    {
        myList.remove(item);
    }
}

for (String item : myList)
{
    System.out.println(item);
}

接着用各种建议解释了如何解决问题。

当我试图重现它时,我没有得到异常! 为什么我没有收到异常?

【问题讨论】:

    标签: java iterator concurrentmodification


    【解决方案1】:

    根据 Java API 文档,Iterator.hasNext 不会抛出 ConcurrentModificationException。

    检查"January" 和"February" 后,您从列表中删除一个元素。调用 it.hasNext() 不会抛出 ConcurrentModificationException 而是返回 false。因此,您的代码干净地退出。然而,最后一个字符串永远不会被检查。如果将"April" 添加到列表中,则会按预期获得异常。

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class Main {
            public static void main(String args[]) {
    
                    List<String> myList = new ArrayList<String>();
                    myList.add("January");
                    myList.add("February");
                    myList.add("March");
                    myList.add("April");
    
                    Iterator<String> it = myList.iterator();
                    while(it.hasNext())
                    {
                        String item = it.next();
                        System.out.println("Checking: " + item);
                        if("February".equals(item))
                        {
                            myList.remove(item);
                        }
                    }
    
                    for (String item : myList)
                    {
                        System.out.println(item);
                    }
    
            }
    }
    

    http://ideone.com/VKhHWN

    【讨论】:

    • 您已经很好地解释了发生的事情,但没有为什么。原因是:它是ArrayList 的迭代器类中的一个错误。
    • 不回答这个问题。但也不是 TJ 所说的错误。
    • 一开始我很困惑,但在 while 循环中添加 print 语句后,它变得清晰了。 Iterator.hasNext 的 API 文档没有说明会抛出 ConcurrentModificationException,因此它确实按设计工作。这有点违反直觉,说实话,我希望hasNext 会在这些情况下抛出。出于性能原因,可能会忽略此检查。
    • “根据 Java API 文档,Iterator.hasNext 不会抛出 ConcurrentModificationException。” Facepalm +1,删除了我的答案。这是严重错误的,但有明确的记录。 :-)
    • 其实连Iterator.next()都没有声明扔CME。只有整个 ArrayList 类的 JavaDoc 说:如果列表在创建迭代器后的任何时候在结构上被修改,除了通过迭代器自己的删除或添加方法之外,迭代器将抛出 ConcurrentModificationException,但没有指定具体的方法。
    【解决方案2】:

    来自ArrayList 来源(JDK 1.7):

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;
    
        public boolean hasNext() {
            return cursor != size;
        }
    
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
    
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
    
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    

    对ArrayList 的每次修改操作都会增加modCount 字段(列表自创建以来被修改的次数)。

    创建迭代器时,它将modCount 的当前值存储到expectedModCount 中。逻辑是:

    • 如果列表在迭代过程中根本没有被修改,modCount == expectedModCount
    • 如果列表被迭代器自己的remove() 方法修改,modCount 会增加,但expectedModCount 也会增加,因此modCount == expectedModCount 仍然成立
    • 如果其他方法(甚至其他迭代器实例)修改列表,modCount 会增加,因此modCount != expectedModCount,这会导致ConcurrentModificationException

    但是,从源代码中可以看出,检查不是在hasNext() 方法中执行的,而是在next() 中执行的。 hasNext() 方法也只比较当前索引和列表大小。当您从列表中删除倒数第二个元素 ("February") 时,这会导致以下对 hasNext() 的调用仅返回 false 并在 CME 可能被抛出之前终止迭代。

    但是,如果您删除了除倒数第二个以外的任何元素,则会引发异常。

    【讨论】:

      【解决方案3】:

      我认为正确的解释是来自 ConcurrentModificationExcetion 的 javadocs 的摘录:

      请注意,通常无法保证快速失败的行为 说,不可能在存在的情况下做出任何硬性保证 不同步的并发修改。快速失败的操作抛出 ConcurrentModificationException 尽最大努力。因此,它 编写一个依赖此异常的程序是错误的 其正确性:仅应使用 ConcurrentModificationException 检测错误。

      因此,如果迭代器快速失败,它可能会抛出异常,但不能保证。尝试在您的示例中将 February 替换为 January 并引发异常(至少在我的环境中)

      【讨论】:

      • 虽然该段落在那里,但请注意其中的警告。与此同时,bikeshedder gets to the crux of the matter: hasNext 不会抛出 ConcurrentModificationException!面对这个简单的事实,我在我的回答(以及你在我们的回答中)的所有分析都是再见。
      【解决方案4】:

      在检查并发修改之前,迭代器检查它是否已经迭代了尽可能多的元素以查看它是否已到达末尾。这意味着如果您只删除倒数第二个元素,您不会在同一个迭代器中看到 CME。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 2021-07-24
        • 2011-08-18
        • 1970-01-01
        相关资源
        最近更新 更多