VOOZH about

URL: https://www.geeksforgeeks.org/java/concurrentmodificationexception-in-java-with-examples/

⇱ ConcurrentModificationException in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ConcurrentModificationException in Java with Examples

Last Updated : 12 Jul, 2025
In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown.
  1. If this exception is detected, then the results of the iteration are undefined.
  2. Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators.
For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed. Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment. If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException. For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException. In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing,
Output:
ArrayList: 
One, 

Trying to add an element in between iteration

java.util.ConcurrentModificationException
To avoid this exception, Example: Let’s see how to resolve this exception by simply changing the place of modification.
Output:
ArrayList: 
One, Two, Three, Four, 

Trying to add an element in between iteration: true

Updated ArrayList: 
One, Two, Three, Four, Five,
From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated.
Comment