Showing posts with label ConcurrentAcessModification. Show all posts
Showing posts with label ConcurrentAcessModification. Show all posts

Sunday, 27 July 2014

ConcurrentAcessModification Exception Java

 

ConcurrentAcessModification Exception Java


This exception does not normally have anything to do with synchronization - it is normally thrown if a Collection is modified while an Iterator is iterating through it. AddAll methods may use an iterator - and its worth noting that the posh foreach loop iterates over instances of Iterator too.

Example - 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class Test{
   
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1,"1");
        map.put(2,"2");
        map.put(3,"3");
        map.put(4,"4");
        map.put(5,"5");
        map.put(6,"6");
        Set keyset = map.keySet();
        Iterator iterator = keyset.iterator();
        while(iterator.hasNext()){
          System.out.println(map.get((Integer)iterator.next()));

          // Here you will get java.lang.ConcurrentAccessModification Exception.
            map.put(6,"6");
            map.put(7,"7");
          
        }
    }

}