我正在调用返回TreeMap
实例的函数,并且在调用代码中我想修改TreeMap
。但是,我得到了ConcurrentModificationException
。
这是我的代码:
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;
}
我的呼叫代码是:
Map<String, String> key_values =Collections.synchronizedMap(Classname.function1());
//here key_values.put() giving ConcurrentModificationException
如果使用ConcurrentSkipListMap,可以更快,并且没有此问题。
public NavigableMap<String, String> function1() {
NavigableMap<String, String> key_values = new ConcurrentSkipListMap<String, String>();
// all key_values.put() goes here
return key_values;
}
请注意,如果您使用的是迭代器,Collections.synchronizedMap
将从不
您似乎正在获取同步地图的同步地图。如果我将对function1()的调用替换为它的内容(简化),我们将得到:
您正在寻找同步的MAP,因此我假设您正在处理多线程应用程序。在这种情况下,如果要使用迭代器,则必须为MAP同步块。
这就是我提出的/*This reference will give error if you update the map after synchronizing values.*/
Map<String, String> values =Collections.synchronizedMap(function1());
/*This reference will not give error if you update the map after synchronizing values */
Map<String, String> values = Collections.synchronizedMap(new TreeMap<String, String>());
synchronized (values)
{
Iterator it = values.entrySet().iterator();
while(it.hasNext())
{
it.next() ;
// You can update the map here.
}
}
: