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:

  1. Collection is modified structurally while fail-fast iterator is iterating through it in the same thread.

  2. 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:

  1. 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 use iterator.remove() method for any structural modification.

  2. 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:
  1. Removing elements while iterating over a Java Collection
  2. Fail-Safe vs Fail-Fast Iterator in Java Collections Framework
  3. Precision and scale for a Double in java
  4. Allow insecure SSL in Java 11 HttpClient
  5. Secure OTP generation in Java
  6. Discuss internals of a ConcurrentHashmap (CHM) in Java
  7. What is volatile keyword in Java

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.