How will you handle ConcurrentModificationException in Java

Carvia Tech | May 06, 2019 | 1 min read | 1,124 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. How will you implement your custom threadsafe Semaphore in Java
  2. Troubleshooting Deadlock in Java
  3. How will you increment each element of an Integer array, using parallel operation
  4. Allow insecure SSL in Java 11 HttpClient
  5. Precision and scale for a Double in java
  6. What do you understand by Java Memory Model?
  7. Removing elements while iterating over a Java Collection

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 week ago

Recommended books for interview preparation:

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