Showing posts with label iterator. Show all posts
Showing posts with label iterator. Show all posts

Tuesday, December 3, 2013

Avoid ConcurrentModificationException when using an Java Iterator

Lets explore this scenario with the following example:
First see two methods and then see last two methods.
For first two methods, used simple arraylist and hashmap, so concurrent exception occurs.
But for the later two methods, used copy on write arraylist and concurrent hashmap, so no problem with the last two methods.

package pritom;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 3/12/13
 * Time: 4:04 PM
 * To change this template use File | Settings | File Templates.
 */
public class ConcurrentModification {
    public static void main(String[] args) {
        ConcurrentModification.concurrentModificationList();
        ConcurrentModification.concurrentModificationHashMap();
        ConcurrentModification.concurrentModificationConcurrentList();
        ConcurrentModification.concurrentModificationConcurrentHashMap();
    }

    private static void concurrentModificationList() {
        try {
            List<String> myDataList = new ArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("Deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationHashMap() {
        try {
            Map<String, String> myDataList = new HashMap<String, String>();
            myDataList.put("0", "00");
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");

            System.out.println("\n\nDeleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Map error: " + ex.toString() + " *****\n\n");
        }
    }

    private static void concurrentModificationConcurrentList() {
        try {
            List<String> myDataList = new CopyOnWriteArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("\n\nDeleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                    myDataList.add("55");
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationConcurrentHashMap() {
        try {
            Map<String, String> myDataList = new ConcurrentHashMap<String, String>();
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");
            myDataList.put("4", "44");

            System.out.println("\n\nDeleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                    System.out.println("Adding: 5 = 55");
                    myDataList.put("5", "55");
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent Map error: " + ex.toString() + " *****\n\n");
        }
    }
}

And see the output


Deleting from List: 
Not deleting: 1
Deleting: 2
***** Deleting from List error: java.util.ConcurrentModificationException *****


Deleting from Map: 
Not deleting: 3 = 33
Deleting: 2 = 22
***** Deleting from Map error: java.util.ConcurrentModificationException *****




Deleting from Concurrent List: 
Not deleting: 1
Deleting: 2
Not deleting: 3
Deleting: 4
After deleting from Concurrent List: 
Remaining: 1
Remaining: 3
Remaining: 55
Remaining: 55


Deleting from Concurrent Map: 
Not deleting: 1 = 11
Not deleting: 3 = 33
Deleting: 4 = 44
Adding: 5 = 55
Deleting: 2 = 22
Adding: 5 = 55
After deleting from Concurrent Map: 
Remaining: 1 = 11
Remaining: 5 = 55
Remaining: 3 = 33

To Avoid ConcurrentModificationException in multi-threaded environment (first two methods):
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.

From the above example its clear that (last two methods):
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.

Thursday, December 13, 2012

Java: iterate through HashMap

Map resultMap = new HashMap();

ResultSet resultSetRegion = s.executeQuery(sSql2);
if(resultSetRegion.next()) {
    resultMap.put( "firstName", "" + resultSetRegion.getString("first_name") );
}

Iterator it = resultMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    System.out.println("KEY: "+pairs.getKey()+"\tVALUE: "+pairs.getValue());
}