TheUnreal
TheUnreal

Reputation: 24472

Removing item from a list inside for - didn't get ConcurrentModificationException

I have the following code:

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);
}

I was expecting to get ConcurrentModificationException since I'm removing an item from the list in the iteration itself, but I didn't.

I was curious how is it possible and why it didn't happen this time?

Upvotes: 1

Views: 52

Answers (1)

Mureinik
Mureinik

Reputation: 311393

You'd get a ConcurrentModificationException is you invalid an iterator used for the loop. Here, you aren't using an iterator, but a simple int to count over the list indexes. You won't get a ConcurrentModificationException, but you will get the wrong result, as you're modifying the list without accounting for it with the index. For example, assume the first three elements in the list are A, B and C (in indexes 0, 1 and 2 respectively). If A is done, you'll remove it, and B will now be at index 0. In the next iteration of the loop, you'll progress to check index 1 which now holds C, without ever evaluating B.

Upvotes: 1

Related Questions