$show=/label

Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException

SHARE:

A quick guide to ConcurrentModificationException and when ConcurrentModificationException occurs. Understanding ConcurrentModificationException internals and exampelprograms.

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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException
Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException
A quick guide to ConcurrentModificationException and when ConcurrentModificationException occurs. Understanding ConcurrentModificationException internals and exampelprograms.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQ4K_p8en5PtkfMbha49Pa3Eno-ZWMp8PIK_u5Nu7bDjG2jyQFbKz11tMIGjEHemdPlJ7v9esaQNC5Zumb2Ay2jS2Zy91r8KcFHBoArgx2BpFl1fXunQgQ40UJ7ldB6svXzcFwU500J8U/s640/Understand+Java+ConcurrentModificationException+and+How+To+Avoid+ConcurrentModificationException.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQ4K_p8en5PtkfMbha49Pa3Eno-ZWMp8PIK_u5Nu7bDjG2jyQFbKz11tMIGjEHemdPlJ7v9esaQNC5Zumb2Ay2jS2Zy91r8KcFHBoArgx2BpFl1fXunQgQ40UJ7ldB6svXzcFwU500J8U/s72-c/Understand+Java+ConcurrentModificationException+and+How+To+Avoid+ConcurrentModificationException.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/03/concurrentmodificationexception.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/03/concurrentmodificationexception.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content