How will you handle ConcurrentModificationException in Java
Carvia Tech | May 06, 2019 | 1 min read | 939 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 use
iterator.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:
- How will you calculate factorial of a large number in Java
- What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
- How will you implement your custom threadsafe Semaphore in Java
- Allow insecure SSL in Java 11 HttpClient
- How will you increment each element of an Integer array, using parallel operation
- Removing elements while iterating over a Java Collection
- What do you understand by Java Memory Model?
Find more on this topic:
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:
- Submit Form with Java 11 HttpClient - Kotlin
- Explain Java Exception Class Hierarchy
- Http download using Java NIO FileChannel
- CRC32 checksum calculation Java NIO
- Set precision and scale for a double value in java
- Difference between HashMap, LinkedHashMap and TreeMap
- What is difference between ExecutorService submit and execute method
- What is left shift right shift and unsigned rght shift operator in Java
- What happens when wait() & notify() method are called
- can we write a java method that swaps two integers