ConcurrentModificationException in Java
Upasana | November 21, 2020 | 1 min read | 1,287 views | Multithreading and Concurrency
ConcurrentModificationException is raised by fail-fast iterators when the underlying collection is modified structurally during iteration.
In the face of concurrent modification, the fail-fast iterator fails quickly and cleanly by throwing ConcurrentModificationException, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
There are two main scenarios when this exception can occur:
- 
Collection is modified structurally while fail-fast iterator is iterating through it in the same thread. 
- 
One thread modifies the structure of collection, while other thread is iterating through it using fail-fast iterator. 
There are two ways to handle this scenario:
- 
Do not allow modification in underlying collection during the iteration. - 
Use synchronization mechanism to prevent any other thread from accessing the collection concurrently. 
- 
Do not use Collection.remove()method instead always useiterator.remove()method for any structural modification.
 
- 
- 
Do not use fail-fast iterators, instead use fail-safe iterators using concurrent collections. For example, ConcurrentHashMap instead of HashMap, CopyOnWriteArrayList instead of ArrayList, etc. Fail-safe iterators do not throw this exception. 
Top articles in this category:
- Removing elements while iterating over a Java Collection
- Fail-Safe vs Fail-Fast Iterator in Java Collections Framework
- Precision and scale for a Double in java
- Allow insecure SSL in Java 11 HttpClient
- Secure OTP generation in Java
- Discuss internals of a ConcurrentHashmap (CHM) in Java
- What is volatile keyword in Java
 
                        