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 未按预期抛出


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01