ConcurrentModificationException in Java with Examples
Last Updated :
02 Apr, 2020
ConcurrentModificationException in Multi threaded environment
In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown.
- If this exception is detected, then the results of the iteration are undefined.
- Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators.
For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed.
ConcurrentModificationException in Single threaded environment
Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment.
If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException.
For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException.
Example: In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing,
import java.util.Iterator;
import java.util.ArrayList;
public class modificationError {
public static void main(String args[])
{
ArrayList<String> arr
= new ArrayList<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.add("Four");
try {
System.out.println(
"ArrayList: ");
Iterator<String> iter
= arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
System.out.println(
"\n\nTrying to add"
+ " an element in "
+ "between iteration\n");
arr.add("Five");
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
ArrayList:
One,
Trying to add an element in between iteration
java.util.ConcurrentModificationException
How to avoid ConcurrentModificationException?
To avoid this exception,
Example: Let’s see how to resolve this exception by simply changing the place of modification.
import java.util.Iterator;
import java.util.ArrayList;
public class modificationError {
public static void main(String args[])
{
ArrayList<String> arr
= new ArrayList<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.add("Four");
try {
System.out.println(
"ArrayList: ");
Iterator<String> iter
= arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
}
System.out.println(
"\n\nTrying to add"
+ " an element in "
+ "between iteration: "
+ arr.add("Five"));
System.out.println(
"\nUpdated ArrayList: ");
iter = arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
ArrayList:
One, Two, Three, Four,
Trying to add an element in between iteration: true
Updated ArrayList:
One, Two, Three, Four, Five,
From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated.
Similar Reads
ConcurrentModificationException in Java with Examples
ConcurrentModificationException in Multi threaded environment In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown. If this e
3 min read
How to Solve ConcurrentModificationException in Java?
An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote fil
4 min read
How to Avoid ConcurrentModificationException in Java?
ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java.util package. Procedure: Some steps are require
4 min read
CloneNotSupportedException in Java with Examples
CloneNotSupportedException is thrown to show that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface. Hierarchy: Those applications which override the clone method can also throw this type of exception to indica
1 min read
ConcurrentModificationException while using Iterator in Java
ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this Concur
3 min read
ConcurrentSkipListSet lower() method in Java with Examples
The lower() method of ConcurrentSkipListSet is used to return the largest element present in this set which is strictly less than the specified element. If there is no such element present in the set, then this function will return null. Syntax: public E lower (E e) Parameters: This method takes onl
2 min read
ConcurrentLinkedDeque pop() method in Java with Examples
The Java.util.ConcurrentLinkedDeque.pop() method in Java is used to pop an element from the ConcurrentLinkedDeque. The element is popped from the top of the ConcurrentLinkedDeque and is removed from the same.Syntax: ConcurrentLinkedDeque.pop() Parameters: The method does not take any parameters.Retu
2 min read
ConcurrentLinkedDeque push() method in Java with Examples
The push() method of ConcurrentLinkedDeque class is an in-built function in Java which pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success an
2 min read
java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples
The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program. Java compiler never checks for this error during compilation. The java.lang.ArrayIndexOutOfBoundsException is one of the most common exceptions in java. It occurs when the progr
2 min read
ConcurrentLinkedDeque remove() method in Java with Examples
The java.util.concurrent.ConcurrentLinkedDeque.remove() is an in-built function in Java which is used to remove an element from this deque.Syntax: public E remove() or public boolean remove(Object o) Parameters: The first overload of this method does not accepts any parameter. However the second ove
2 min read