java.util.ConcurrentModificationException 未按预期抛出

java.util.ConcurrentModificationException not thrown when expected(java.util.ConcurrentModificationException 未按预期抛出)

本文介绍了java.util.ConcurrentModificationException 未按预期抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码抛出 java.util.ConcurrentModificationException,正如预期的那样:

The following code throws a java.util.ConcurrentModificationException, as expected:

   public void test(){
      ArrayList<String> myList = new ArrayList<String>();

      myList.add("String 1");
      myList.add("String 2");
      myList.add("String 3");
      myList.add("String 4");
      myList.add("String 5");

      for(String s : myList){
         if (s.equals("String 2")){
            myList.remove(s);
         }
      }
   }

但是,以下代码不会抛出异常,而我希望它会被抛出:

However, the following code does not throw the Exception, while I expect it to be thrown:

   public void test(){
      ArrayList<String> myList = new ArrayList<String>();

      myList.add("String 1");
      myList.add("String 2");
      myList.add("String 3");

      for(String s : myList){
         if (s.equals("String 2")){
            myList.remove(s);
         }
      }
   }

区别在于第一个列表包含5个项目,而第二个列表包含3个.使用的JVM是:

The difference is that the first list contains 5 items, while the second list contains 3. The JVM used is:

java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

问题:为什么第二段代码NOT会抛出java.util.ConcurrentModificationException?

The question: why does the second piece of code NOT throw the java.util.ConcurrentModificationException?

推荐答案

在实现中从 ArrayList.iterator() 返回的迭代器显然都在调用中仅使用检查结构修改next()not 在对 hasNext() 的调用中.后者看起来像这样(在 Java 8 下):

The iterator returned from ArrayList.iterator() in the implementation we're apparently both using only checks for structural modification in calls to next(), not in calls to hasNext(). The latter just looks like this (under Java 8):

public boolean hasNext() {
    return cursor != size;
}

所以在你的第二种情况下,迭代器知道"它返回了两个元素,并且列表只有 两个元素......所以 hasNext() 只是返回 false,我们永远不会第三次调用 next().

So in your second case, the iterator "knows" that it's returned two elements, and that the list only has two elements... so hasNext() just returns false, and we never end up calling next() the third time.

我认为这是一个实现细节 - 基本上检查没有尽可能严格.在这种情况下,hasNext() 执行检查并抛出异常也是完全合理的.

I would view this as an implementation detail - basically the checking not being as strict as it could be. It would be entirely reasonable for hasNext() to perform a check and throw an exception in this case too.

这篇关于java.util.ConcurrentModificationException 未按预期抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:java.util.ConcurrentModificationException 未按预期抛出

基础教程推荐