是否避免TreeMap ConcurrentModificationException?

问题描述 投票:12回答:5

我正在调用返回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
java treemap concurrentmodification
5个回答
6
投票

如果使用ConcurrentSkipListMap,可以更快,并且没有此问题。

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

    return key_values;
}

15
投票

请注意,如果您使用的是迭代器,Collections.synchronizedMap从不


1
投票

您似乎正在获取同步地图的同步地图。如果我将对function1()的调用替换为它的内容(简化),我们将得到:


1
投票

您正在寻找同步的MAP,因此我假设您正在处理多线程应用程序。在这种情况下,如果要使用迭代器,则必须为MAP同步块。


0
投票

这就是我提出的/*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. } }

© www.soinside.com 2019 - 2024. All rights reserved.