Search code examples
javatreemapconcurrentmodification

Avoiding TreeMap ConcurrentModificationException?


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

Solution

  • If you use a ConcurrentSkipListMap is can be faster and doesn't have this issue.

    public NavigableMap<String, String> function1() {
        NavigableMap<String, String> key_values = new ConcurrentSkipListMap<String, String>();
        // all key_values.put() goes here
    
        return key_values;
    }
    

    If you don't need the keys to be sorted you can use a ConcurrentHashMap.