java.util.ConcurrentModificationException不希望抛出 [英] java.util.ConcurrentModificationException not thrown when expected

查看:120
本文介绍了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()返回的迭代器在 hasNext() next() $ C>。后者只是这样(在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,我们从不会调用$ code> 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不希望抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆