Saturday, 27 December 2014

How to resolve Concurrent Modification Exception In Java

1. Concurrent modification exception occurs, when you are modifying an object such as a collection, which is not permissible.
2. This exception may also arise, when one thread is iterating over a collection, while another thread is trying to modify the same collection.
3. Note that this exception does not always indicate that an object has been concurrently modified by a different thread.  For example, In a program, when iterating over a set, this exception arises if you directly remove elements from set using set.remove(anObject), instead of iterator.remove().

Program which throws Concurrent Modification Exception :

Import java.util.Set;
import java.util.HashSet;

public class CmeExample {
 Public static void main(String args[]) {
  Set aSet = new HashSet();
  for(String value : aSet) {
   if(value.equals(“DEF”) {

4. If you run the above program, you'll get the below exception
  Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(
        at java.util.HashMap$
        at CmeExample.main(

5. In the above program, we are removing an element from the Set "aSet", using it's method remove(anObj), this resulted the concurrent modification exception.
6. The Solution to this is

Solution :

1. Use iterator.remove() method instead of collection’s remove(anObject) method.
2. For this, always use iterator instead of enhanced for loop to iterate over a collection, because even though enhanced for loop, uses a iterator, but you’ll not have access to it’s remove metod, so always use the corresponding collection’s iterator, by calling it’s iterator() method.
3. Let’s see the same code with some changes to resolve this issue.
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class CmeExample {
   public static void main(String args[]) {
 Set aSet = new HashSet();
 /*for(String value : aSet) {
 if(value.equals("DEF") ){
 Iterator setIterator = aSet.iterator();
 String setItem = "";
 while(setIterator.hasNext()) {
  setItem =;
  if(setItem.equals("DEF")) {
   System.out.println(setItem + " removed");
4. If you run the above program, now you won't get concurrent modification exception. 


Post a Comment

Note: only a member of this blog may post a comment.