How will you handle ConcurrentModificationException in Java

Carvia Tech | May 06, 2019 | 1 min read | 19 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. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  2. How will you calculate factorial of a large number in Java
  3. Removing elements while iterating over a Java Collection
  4. How will you implement your custom threadsafe Semaphore in Java
  5. How will you increment each element of an Integer array, using parallel operation
  6. What do you understand by Java Memory Model?
  7. What is ThreadLocal in Java, where will you use this class



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info