Skip to content
Advertisement

Why does this Java code trigger a ConcurrentModificationException?

In the first line of the loop I get the error, but I don’t see why. From what I read this should happen only if I’m iterating over a collection and trying to modify it at the same time, but this is not the case.

In the code, list is of type ArrayList<Product>.

JavaScript

This is the stacktrace:

JavaScript

Advertisement

Answer

subList does not create a new list that has the same elements as the original list in the specified range. Rather, it creates a “view” (docs):

Returns a view of the portion of this list […]. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

Also note:

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list.

This is exactly what you are doing in merge. You are creating sublists left. Then modifying left structurally with add. So far so good. But then you created another sublist right and modifies it as well. This makes “the semantics of left to become undefined”. And this causes the next call to get to throw an exception.

Minimal reproducible example:

JavaScript

Sublists are a bit like iterators in this regard (you can only remove via the iterator, if you remove via the original list, CME might be thrown).

One simple way to fix this is to create copies of the sublists so that they are no longer “views”, but are actually independent lists:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement