首页 > 解决方案 > 从内部列表中删除项目 - 没有得到 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,因为我正在从迭代本身的列表中删除一个项目,但我没有。

我很好奇这怎么可能,为什么这次没有发生?

标签: javalist

解决方案


你会得到一个ConcurrentModificationException用于循环的迭代器是否无效。在这里,您没有使用迭代器,而是简单int地计算列表索引。你不会得到 a ConcurrentModificationException,但你会得到错误的结果,因为你正在修改列表而不用索引来解释它。例如,假设列表中的前三个元素是 A、B 和 C(分别在索引 0、1 和 2 中)。如果 A 完成,您将删除它,B 现在将位于 index 0。在循环的下一次迭代中,您将继续检查现在包含 C 的索引 1,而无需评估 B。


推荐阅读