代码如下所示:这里使用的地图是 Guava 地图
private Map<SomeObject, SomeOtherObject> myMap = Maps.newLinkedHashMap();
public Map<SomeObject, SomeOtherObject> getMap() {
return Maps.newHashMap(myMap);
}
public void putMap(SomeObject a, SomeOtherObject b) {
myMap.put(a,b);
}
所以,上面抛出java.util.ConcurrentModificationException
并试图重新创建场景。但无论我尝试什么,系统似乎都具有弹性。这是我尝试过的:
1. Created 'n' threads some of which call getMap() and some call putMap()
2. Created 'n' threads that only call putMap() and one thread the is in an infinite loop that calls getMap()
3. Created 2 threads each of which alternates calling getMap() and putMap(). Meaning, thread-1 first calls get then put and thread-2 first calls put and then get.
以上都不起作用,要么继续运行,要么进入 OOM。有关如何执行此操作的任何指示?
编辑
我相信返回地图{ }ConcurrentModificationException
的副本时会抛出。Maps.newHashMap(myMap);
在这个过程中,迭代器创建了一个副本,当迭代器工作时,如果地图的内容被修改,它就会不高兴。