代码之家  ›  专栏  ›  技术社区  ›  TheUnreal

正在从的列表中删除项目-未获得ConcurrentException

  •  0
  • TheUnreal  · 技术社区  · 6 年前

    我有以下代码:

    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

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

    0 回复  |  直到 6 年前
        1
  •  1
  •   Mureinik    6 年前

    你会得到一个 ConcurrentModificationException 循环使用的迭代器无效。这里,您使用的不是迭代器,而是一个简单的 int ,但您将得到错误的结果,因为您在修改列表时没有使用索引对其进行说明。例如,假设列表中的前三个元素是A、B和C(分别在索引0、1和2中)。如果A完成了,您将删除它,B现在将处于索引位置 0 .在循环的下一次迭代中,您将继续检查索引1,它现在包含C,而不计算B。