java - 从内部列表中删除项目 - 没有得到 ConcurrentModificationException
问题描述
我有以下代码:
for (int i = 0; i < this.batchFutures.size(); i++) {
Future<AbstractMap.SimpleEntry<Location, String>> result = this.batchFutures.get(i);
Map.Entry<Location, String> entry = null;
try {
if (result.isDone()) {
entry = result.get();
this.updateStatisticsFor(entry.getValue(), "success");
this.clearAfterSent(i, entry);
}
} catch (Exception e) {
logger.error("Error", e);
this.updateStatisticsFor(entry.getValue(), "fail");
this.clearAfterSent(i, entry);
}
}
private void clearAfterSent(
int i,
Map.Entry<SdavcAmazonRequestMsg.DataAffinity, ImmutableList<TelemetryMeta>> entry) {
this.batchFutures.remove(i);
}
我期待得到ConcurrentModificationException
,因为我正在从迭代本身的列表中删除一个项目,但我没有。
我很好奇这怎么可能,为什么这次没有发生?
解决方案
你会得到一个ConcurrentModificationException
用于循环的迭代器是否无效。在这里,您没有使用迭代器,而是简单int
地计算列表索引。你不会得到 a ConcurrentModificationException
,但你会得到错误的结果,因为你正在修改列表而不用索引来解释它。例如,假设列表中的前三个元素是 A、B 和 C(分别在索引 0、1 和 2 中)。如果 A 完成,您将删除它,B 现在将位于 index 0
。在循环的下一次迭代中,您将继续检查现在包含 C 的索引 1,而无需评估 B。
推荐阅读
- oracle - 如何找到Oracle Forms接口集成的PL/SQL程序
- optimization - BARON ERROR:在 Julia 中使用 JuMP 时无法打开 nl 文件
- awk - awk 命令意外换行符或字符串结尾
- asp.net-core - 如果我的站点将使用 Web api 进行后端工作,那么“Asp.Net Core 托管”Blazor WebAssembly 服务器站点可以提供什么功能?
- javascript - 是否可以将jpg图像转换为bmp?
- python - rasa.core.agent - 由于找不到模块“rasa.nlu.classifiers.fallback_classifier”而无法加载模型
- wordpress - Nginx 加载资源失败:服务器对 png 文件响应状态为 404()
- docker - MinIO STS:无法获取临时凭证
- ruby-on-rails - Ruby:通过时间戳循环并跳回循环 - 优化
- loops - Roblox:我怎样才能让这个脚本正常工作?