Search code examples
javaexceptionsetconcurrentmodification

ConcurentModificationException when using Set


The runtime indicates the exception occurs when giving temp = keysit.next(). I thought this had been taken care of when I redefined keysit = keys.iterator() for the 2nd time, but maybe I'm missing the point. Any suggestions?

Map<Integer, Set<String>> lhm = new LinkedHashMap<Integer, Set<String>>();

public void sortMap() {
    Set<Integer> keys = hm.keySet();
    Iterator<Integer> keysit;
    int iterations = keys.size();
    int smallest;
    int temp;
    for(int i=0; i<iterations; i++) {
        keysit = keys.iterator();
        smallest = keysit.next();
        keysit = keys.iterator();  
        while(keysit.hasNext()) {
            temp = keysit.next();  
            if(temp<smallest) 
                smallest = temp;
            lhm.put(smallest, lhm.get(smallest));
            keys.remove(smallest);
        }
    }
    System.out.println(lhm);
}

Solution

  • The point is iterator maintains an integer flag named - modCount which keep track of modifications during iteration.

    In following line of code

    keys.remove(smallest);
    

    you are actually removing element from the set which changes this modcount. So next time when next() is called to get the next element, it checks whether modcount value has been changed or not. If yes then throw concurrent modification exception.

    So all in all the modification is dependent on the modcount flag and doesn't depend on how many times you redefine keys.iterator().

    One good option is to use ConcurrentHashMap as suggested by @Olu