ConcurrentModificationException is thrown when two threads are updating the same element on same time. This issue occurs often in the multithreaded environment. However, this also can occur in the single thread environment where same application running the multiple threads which updates the same object.
Look at this example which throws ConcurrentModificationException while updating the value “three”.
package javabeat.net.core; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * ConcurrentModificationException Example * @author krishna * */ public class ConcurrentModificationExceptionExample { public static void main(String args[]){ List<String> myNumbersList = new ArrayList<String>(); myNumbersList.add("one"); myNumbersList.add("two"); myNumbersList.add("three"); myNumbersList.add("four"); myNumbersList.add("five"); Iterator<String> numIterator = myNumbersList.iterator(); while(numIterator.hasNext()){ String value = numIterator.next(); System.out.println("Value:"+value); if(value.equals("three")) myNumbersList.remove(value); } Map<String,String> numMap = new HashMap<String,String>(); numMap.put("one", "one"); numMap.put("two", "two"); numMap.put("three", "three"); Iterator<String> keyIterator = numMap.keySet().iterator(); while(keyIterator.hasNext()){ String key = keyIterator.next(); System.out.println("Map Value:"+numMap.get(key)); if(key.equals("two")){ numMap.put("one","four"); //numMap.put("four", "four"); } } } }
Output
Value:one Value:two Value:three Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:782) at java.util.ArrayList$Itr.next(ArrayList.java:754) at javabeat.net.core.ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:23)
If you look at the above code, the exception is thrown at the iterator.next() call. This checks for the modification of the object and internally calls the checkForComodification() to see any other modifications done. To make this program work, remove the commented line and run the program. It will work and print the complete output.
Since we are updating the existing key value in the numMap, its size is not been changed and we are not getting ConcurrentModificationException. I hope this example helps you to understand the ConcurrentModificationException.