java.util.ConcurrentModificationException | Code Factory

Reference Link : Link

Donate : Link

java.util.ConcurrentModificationException is a very common exception when working with Java collection classes. Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the will throw ConcurrentModificationException. Concurrent modification exception can come in case of multithreaded as well as a single threaded java programming environment.

Let’s see the concurrent modification exception scenario with an example.

Above program will throw java.util.ConcurrentModificationException when executed, as shown in below console logs.

Output :

From the output stack trace, its clear that the concurrent modification exception is coming when we call iterator next() function. If you are wondering how Iterator checks for the modification, its implementation is present in AbstractList class where an int variable modCount is defined. modCount provides the number of times list size has been changed. modCount value is used in every next() call to check for any modifications in a function checkForComodification().

Now comment out the list part and run the program again. You will see that there is no ConcurrentModificationException being thrown now.

Output will be :

Since we are updating the existing key value in the myMap, its size has not been changed and we are not getting ConcurrentModificationException. Note that the output may differ in your system because HashMap keyset is not ordered like a List. If you will uncomment the statement where I am adding a new key-value in the HashMap, it will cause ConcurrentModificationException.

To Avoid ConcurrentModificationException in multi-threaded environment

  • You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
  • You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
  • If you are using JDK 1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. This is the recommended approach to avoid concurrent modification exception.

Let us run an example using Concurrent Collection classes :

The output of the above program is shown below. You can see that there is no ConcurrentModificationException being thrown by the program.

Output :



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store