java.util.concurrentmodificationexception with example in Java

java.util.ConcurrentModificationException is a very common exception when working with Java collection classes. Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.

Concurrent modification exception can come in case of multithreaded as well as a single threaded java programming environment.

public class ConcurrentModificationException
extends RuntimeException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. For more info Java Online Classes

Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected.

Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected.

Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future. Get additional info from Core Java Online Training

To Avoid ConcurrentModificationException in multi-threaded environment

  1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
  2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
  3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. This is the recommended approach to avoid concurrent modification exception.

To Avoid ConcurrentModificationException in single-threaded environment

You can use the iterator remove() function to remove the object from underlying collection object. But in this case, you can remove the same object and not any other object from the list.

Iterator’s remove method

In a single-threaded environment, use the iterator’s remove method, in order to concurrently iterate over a collection and remove things from it. For example:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class Example_v4 {
 
     public static void main(String[] args) {
          List<String> list = new ArrayList<String>();
 
          // Insert some sample values.
          list.add("Value1");
          list.add("Value2");
          list.add("Value3");
 
          // Get an iterator.
          Iterator<String> ite = list.iterator();
 
          /* Remove the second value of the list, while iterating over its elements,
           * using the iterator's remove method. */
          while(ite.hasNext()) {
               String value = ite.next();
               if(value.equals("Value2"))
                    ite.remove();
               else
                    System.out.println(value);
          }
     }
}

Synchronized Collections

In addition to their default implementations, Java provides a synchronized implementation of a Map, a List, a Set, a Collection, etc. through the Collections class.

Moreover, Java provides the CopyOnWriteArrayList class, in which all mutative operations are implemented by making a fresh copy of the underlying array. Finally, Java also provides the ConcurrentHashMap class, which offers full concurrency of retrievals and adjustable expected concurrency for updates.

All referenced implementations are thread safe. However, the usage of such data structures may also reduce the performance of your application, as thread synchronization spends CPU cycles.

To conclude, all aforementioned methods aim to eliminate the ConcurrentModificationException. However, in a multi-threaded environment this elimination usually comes with the cost of thread synchronization.

In any case, each application has its own specifications and requirements and thus, a meticulous design and implementation are very important in order for such exceptions to be eliminated.

Example:

import java.awt.List;  
import java.util.*;  
  
public class concurrentmodificationexception {  
  
    public static void main(String[] args) {  
          
        HashMap<Integer, Integer> map = new HashMap<>();  
        map.put(1, 1);  
        map.put(2, 2);  
        map.put(3,3);  
          
        Iterator<Integer> it = map.keySet().iterator();  
        while(it.hasNext()) {  
            Integer key = it.next();  
            System.out.println("Map Value:" + map.get(key));  
            if (key.equals(2)) {  
                map.put(1, 4);  
            }  
        }     
    }  
}  

Constructors of ConcurrentModificationException

There are 4 types of constructors of ConcurrentModificationException –

  1. public ConcurrentModificationException()-
    This creates a ConcurrentModificationException with no parameters.
  2. public ConcurrentModificationException(String message)
    This creates a ConcurrentModificationException with a detailed message specifying the Exception.
  3. public ConcurrentModificationException(Throwable cause)
    This creates a ConcurrentModificationException with a cause and a message which is (cause==null?null:cause.toString()). The cause is later retrieved by the Throwable.getCause().
  4. public ConcurrentModificationException(String message, Throwable cause)
    This creates a ConcurrentModificationException with a detailed message and a cause. (cause==null?null:cause.toString()). The message is later retrieved by Throwable.getMessage() and cause is later retrieved by Throwable.getCause().

To get in-depth knowledge, enroll for a live free demo on Java Online Training

Leave a comment

Design a site like this with WordPress.com
Get started