Avoiding TreeMap ConcurrentModificationException?

Nagappa L M picture Nagappa L M · Dec 18, 2012 · Viewed 10.5k times · Source

I am calling function that returns TreeMap instance, and in the calling code I wanted to modify the TreeMap. However, I am getting a ConcurrentModificationException.

Here is my code:

public Map<String, String> function1() {
    Map<String, String> key_values = Collections.synchronizedMap(new TreeMap<String, String>());
    // all key_values.put() goes here

    return key_values;
}

And my calling code is:

Map<String, String> key_values =Collections.synchronizedMap(Classname.function1());
//here key_values.put() giving ConcurrentModificationException

Answer

Brian picture Brian · Dec 18, 2012

Note that Collections.synchronizedMap will never protect you from concurrent modification if you're using an iterator. In addition, unless you're accessing your Map from more than one thread, creating the synchronized map is useless. Locally-scoped collections and variables that are not being handed to other threads do not need to be synchronized.

My guess is that in the code you left out, you're iterating over one of Map.entrySet, Map.keySet, or Map.values, and calling put during that iteration (within the for loop). With the code you've shown, this is the only way this could happen.