java.util.ConcurrentModificationException not thrown when expected(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 未按预期抛出


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01