Misnomer: ConcurrentModificationException

This one actually comes from their own youtube channel. In this short video from their series “Cracking the Java Coding Interview“, the host explains that “the ConcurrentModificationException that you get has in fact nothing to do with concurrency.”

Here’s the video:

However, you can actually cause this problem when you modify a list from another Thread. This shouldn’t happen because modifying a data structure, that isn’t thread-safe, from multiple threads would be a major mistake. And thread-safe implementations don’t have that problem.

Usually, it happens when you iterate a collection and then call some method that changes that same collection. It’s only “concurrent” in the sense that it happens while the iteration takes place, in between two calls to next(). You can simply use the iterator to add or remove elements so it can still be used, because then the iterator knows about those modifications.

And still, the Java docs say this:

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it.

It’s not wrong and it really is just one example, but the threads are not necessary. And this is also explained in the Java docs:

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

Since “concurrent” is associated with multi-threading, it would have been better to call it SimultaneousModificationException, but this would still suggest it’s happening at the same time. ModificationDuringIterationException or ModifiedWhileIteratingException would have been much better names. But of all the misnomers in Java, this one really isn’t such a big deal.

Leave a Reply