ConcurrentModificationException in Java
The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes.
For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it. This is because the result of the iteration becomes undefined with it. Some implementation of the Iterator class throws this exception, including all those general-purpose implementations of Iterator which are provided by the JRE. Iterators which do this are called fail-fast as they throw the exception quickly as soon as they encounter such situation rather than facing undetermined behavior of the collection any time in the future.
Note: It is not mandatory that this exception will be thrown only when some other thread tries to modify a Collection object. It can also happen if a single thread has some methods called which are trying to violate the contract of the object. This may happen when a thread is trying to modify the Collection object while it is being iterated by some fail-fast iterator, the iterator will throw the exception.
This message says that the exception is thrown when the next method is called as the iterator is iterating the list and we are making modifications in it simultaneously. But if we make modifications in hashmap like given below, then it will not throw any such exception as the size of the hashmap won't change.
Map Value:1 Map Value:2 Map Value:3
This example works completely fine as while the iterator is iterating over the map, the size of the map is not changing. Only the map is being updated in the if statement.
Constructors of ConcurrentModificationException
There are 4 types of constructors of ConcurrentModificationException -
How to avoid ConcurrentModificationException in a multi-threaded environment?
To avoid the ConcurrentModificationException in a multi-threaded environment, we can follow the following ways-
How to avoid ConcurrentModificationException in a single-threaded environment?
By using iterator's remove() function, you can remove an object from an underlying collection object.