Pages

Monday, March 30, 2020

Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException

1. Introduction 


In this article, We'll learn when ConcurrentModificationException exception is thrown and what are the reasons java API throws this exception. This is part of java.util package.

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

Most of the collection API classes throw this exception such as ArrayList, HashMap, LinkedList classes. The main reason to throw this exception if any list or map is modified when a loop list or map through the iterator. If the collection is modified when it is looped over Iterator, iterator.next() will thorough ConcurrentModificationException exception. This exception mainly comes into existence in the multithreaded environment. If any collection produces this exception then it is fail-fast and should not be used by multiple threads.


Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException



2. ConcurrentModificationException By Single Thread


This exception does not always indicate that an object has been concurrently modified by a different thread. This can be done by single thread as below example.

package com.java.w3schools.blog.exceptions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * ConcurrentModificationException Example
 * 
 * @author javaProgramTo.com
 *
 */

public class ConcurrentModificationExceptionExample {

 public static void main(String[] args) {

  List<String> values = new ArrayList<String>();

  values.add("Corona");
  values.add("Ebola");
  values.add("Flu");

  Iterator<String> it = values.iterator();

  while (it.hasNext()) {
   String value = it.next();
   System.out.println(value);

   if (value.equals("Corona")) {
    values.add("VOVID 19");

   }

  }
 }

}

Output:

Corona
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
 at java.util.ArrayList$Itr.next(ArrayList.java:859)
 at com.java.w3schools.blog.exceptions.ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:29)

HashMap ConcurrentModificationException Example:


public class ConcurrentModificationExceptionHashMapExample {

 public static void main(String[] args) {

  Map<String, String> values = new HashMap<String, String>();

  values.put("Corona", "8000001");
  values.put("Ebola", "100000");
  values.put("Flu", "1B");

  Iterator<String> it = values.keySet().iterator();

  while (it.hasNext()) {
   String value = it.next();
   System.out.println(value);

   if (value.equals("Corona")) {
    values.put("COVID 19", "10,00,000");

   }

  }
 }

}

3. Exact Reason To ConcurrentModificationException


Let us understand a little bit about how ArrayList works internally.
ArrayList has a private instance variable size and this value will be incremented by 1 when a value-added to ArrayList using add() method and size will be decremented by 1 when remove() method is invoked. As of now after calling add() method on collection API size will be having some value.

WeakHashMap Examples

Along with the size, Collection API maintains another private instance variable "modCount". ArrayList maintains modCount value always the same as size.

Let us consider the above example.

After adding "Corona", "Ebola", "Flu" values, the size will be 3 and modCount will be 3.

Invoke iterator() method on the list as values.iterator() and that returns an Iterator instance.

The iterator class has its own variable that stores list modCount value. Here, Iterators stores expectedModCount as size 3.

When a list is added with new values list modCount will be modified and iterator expectedModCount will be different as below.

modCount = 4;
expectedModCount = 3;

Now, it.next() checks internally always modCount and expectedModCount should be same but in our case now it is different and will throw ConcurrentModificationException.

final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

4. How to Avoid ConcurrentModificationException in Single Or Multi-Threaded Env


To avoid the ConcurrentModificationException exception, We need to use a synchronized block or convert List to Array to iterate or should use CopyOnWriteArrayList, ConcurrentHashMap classes work in the concurrent atmosphere.


4.1 CopyOnWriteArrayList Example


Let us replace the ArrayList with CopyOnWriteArrayList class and try to add the values while looping by the iterator.

public class AvoidConcurrentModificationException {

 public static void main(String[] args) {

  // CopyOnWriteArrayList example
  List<Integer> numbers = new CopyOnWriteArrayList<Integer>();

  numbers.add(100);
  numbers.add(200);
  numbers.add(300);
  numbers.add(400);
  numbers.add(500);

  Iterator<Integer> safeIterator = numbers.iterator();

  while (safeIterator.hasNext()) {

   int n = safeIterator.next();

   if (n > 300) {
    numbers.add(n + 1);
   }
   System.out.print(n + " ");

  }

  System.out.println("\nModifed list : " + numbers);
  
  

 }

}


Output:

This program does not throw any runtime exception because this class has no logic for mod count checking. 

100 200 300 400 500 
Modifed list : [100, 200, 300, 400, 500, 401, 501]

4.2 ConcurrentHashMap Example


Replacing the HashMap with ConcurrentHashMap that does not produce run time exception and produces output.

public class AvoidConcurrentModificationHashMapException {

 public static void main(String[] args) {
  // ConcurrentHashMap example
  Map<Integer, String> numbers = new ConcurrentHashMap<Integer, String>();

  numbers.put(1, "One");
  numbers.put(2, "Two");
  numbers.put(3, "Three");
  numbers.put(4, "Four");

  Iterator<Integer> safeIterator = numbers.keySet().iterator();

  while (safeIterator.hasNext()) {

   int n = safeIterator.next();

   if (n > 2) {
    numbers.put(n + 100, "Modified");
   }
   System.out.print(n + " ");

  }

  System.out.println("\nModifed list : " + numbers.keySet());
 }

}

Full Source Code


5. Conclusion


In this article, We have seen the understanding of runtime exception ConcurrentModificationException and when it will be thrown and how to avoid in concurrency.

GitHub

Ref 1
Ref 2

No comments:

Post a Comment

Please do not add any spam links in the comments section.