terça-feira, 10 de novembro de 2015

ConcurrentModificationException

Referência: http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html


How to Avoid ConcurrentModificationException when using an Iterator

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a ConcurrentModificationException.
This situation can come in case of multithreaded as well as single threaded environment.
Lets explore this scenario with the following example:
01import java.util.*;
02  
03public class IteratorExample {
04  
05    public static void main(String args[]){
06        List<String> myList = new ArrayList<String>();
07  
08        myList.add("1");
09        myList.add("2");
10        myList.add("3");
11        myList.add("4");
12        myList.add("5");
13  
14        Iterator<String> it = myList.iterator();
15        while(it.hasNext()){
16            String value = it.next();
17            System.out.println("List Value:"+value);
18            if(value.equals("3")) myList.remove(value);
19        }
20  
21        Map<String,String> myMap = new HashMap<String,String>();
22        myMap.put("1""1");
23        myMap.put("2""2");
24        myMap.put("3""3");
25  
26        Iterator<String> it1 = myMap.keySet().iterator();
27        while(it1.hasNext()){
28            String key = it1.next();
29            System.out.println("Map Value:"+myMap.get(key));
30            if(key.equals("2")){
31                myMap.put("1","4");
32                //myMap.put("4", "4");
33            }
34        }
35  
36    }
37}
Output is:
1List Value:1
2List Value:2
3List Value:3
4Exception in thread "main" java.util.ConcurrentModificationException
5    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
6    at java.util.AbstractList$Itr.next(AbstractList.java:343)
7    at com.journaldev.java.IteratorExample.main(IteratorExample.java:27)
From the output stack trace, its clear that the exception is coming when we call iterator next() function. If you are wondering how Iterator checks for the modification, its implementation is present in AbstractList class where an int variable modCount is defined that provides the number of times list size has been changed. This value is used in every next() call to check for any modifications in a function checkForComodification().
Now comment the list part and run the program again.
Output will be:
1Map Value:3
2Map Value:2
3Map Value:4
Since we are updating the existing key value in the myMap, its size has not been changed and we are not getting ConcurrentModificationException. Note that the output may differ in your system because HashMap keyset is not ordered like list. If you will uncomment the statement where I am adding a new key-value in the HashMap, it will cause ConcurrentModificationException.
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. It is the recommended approach.
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.
Let us run an example using Concurrent Collection classes:
01package com.journaldev.java;
02  
03import java.util.Iterator;
04import java.util.List;
05import java.util.Map;
06import java.util.concurrent.ConcurrentHashMap;
07import java.util.concurrent.CopyOnWriteArrayList;
08  
09public class ThreadSafeIteratorExample {
10  
11    public static void main(String[] args) {
12  
13        List<String> myList = new CopyOnWriteArrayList<String>();
14  
15        myList.add("1");
16        myList.add("2");
17        myList.add("3");
18        myList.add("4");
19        myList.add("5");
20  
21        Iterator<String> it = myList.iterator();
22        while(it.hasNext()){
23            String value = it.next();
24            System.out.println("List Value:"+value);
25            if(value.equals("3")){
26                myList.remove("4");
27                myList.add("6");
28                myList.add("7");
29            }
30        }
31        System.out.println("List Size:"+myList.size());
32  
33        Map<String,String> myMap =
34             new ConcurrentHashMap<String,String>();
35        myMap.put("1""1");
36        myMap.put("2""2");
37        myMap.put("3""3");
38  
39        Iterator<String> it1 = myMap.keySet().iterator();
40        while(it1.hasNext()){
41            String key = it1.next();
42            System.out.println("Map Value:"+myMap.get(key));
43            if(key.equals("1")){
44                myMap.remove("3");
45                myMap.put("4""4");
46                myMap.put("5""5");
47            }
48        }
49  
50        System.out.println("Map Size:"+myMap.size());
51    }
52  
53}
Output is:
01List Value:1
02List Value:2
03List Value:3
04List Value:4
05List Value:5
06List Size:6
07Map Value:1
08Map Value:null
09Map Value:4
10Map Value:2
11Map Size:4
From the above example its clear that:
1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException.
2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list.
3. In case of ConcurrentHashMap, the behavior is not always the same.
For condition:
1if(key.equals("1")){
2    myMap.remove("3");
Output is:
1Map Value:1
2Map Value:null
3Map Value:4
4Map Value:2
5Map Size:4
It is taking the new object added with key “4? but not the next added object with key “5?.
Now if I change the condition to
1if(key.equals("3")){
2    myMap.remove("2");
Output is:
1Map Value:1
2Map Value:3
3Map Value:null
4Map Size:4
In this case its not considering the new added objects.
So if you are using ConcurrentHashMap then avoid adding new objects as it can be processed depending on the keyset. Note that the same program can print different values in your system because HashMap keyset is not in any order.
Extra Toppings:
1for(int i = 0; i<myList.size(); i++){
2    System.out.println(myList.get(i));
3    if(myList.get(i).equals("3")){
4        myList.remove(i);
5        i--;
6        myList.add("6");
7    }
8}
If you are working on single-threaded environment and want your code to take care of the extra added objects in the list then you can do so using following code and avoiding iterator.
Note that I am decreasing the counter because I am removing the same object, if you have to remove the next or further far object then you don’t need to decrease the counter.
Try it yourself.