本文介绍了Java并发修改异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,导致并发修改异常。我该如何防止?这个想法是逃避地图的所有值,并用新的参数映射重建对象(dO)。

  try {
Map< String,String []> paramMap = dO.getParameterMap();
设置< Map.Entry< String,String []>> entries = paramMap.entrySet();
迭代器< Map.Entry< String,String []>> it = entries.iterator();
while(it.hasNext()){
Map.Entry< String,String []> entry = it.next();
String [] values = entry.getValue();
列表< String> valList = new ArrayList< String>();
if(values!= null){
for(String value:values){
valList.add(escapeHTML(value));
}
dO.removeParameter(entry.getKey());

//请注意,Parameter是一个hashMap,所以在插入前需要先删除该条目或者它将替换与键相关联的新值。如何在Java中工作?

  dO.addParameter(entry.getKey(),valList.toArray(new String [valList.size ()])); 
}
}
}


解决方案

异常被抛出,因为您在迭代它时从地图中添加/删除东西:

  dO。 removeParameter(entry.getKey()); 
dO.addParameter(entry.getKey(),valList.toArray(new String [valList.size()]

应该使用 iterator.remove()


I have written following code which is resulting in concurrent modification exception. How can I prevent it ? The idea is to escape all values of the Map and reconstruct the object (dO) back with new param map.

    try {
        Map<String,String[]> paramMap = dO.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = paramMap.entrySet();
        Iterator<Map.Entry<String, String[]>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> entry = it.next();
            String[] values = entry.getValue();
            List<String> valList = new ArrayList<String>();
            if (values != null) {
                for (String value : values) {
                    valList.add(escapeHTML(value));
                     }
                dO.removeParameter(entry.getKey());

//Please note that Parameter is a hashMap so , Is it required to remove the entry first before inserting or it will replace the new value associated with key . How it works in Java ?

                dO.addParameter(entry.getKey(),valList.toArray(new String[valList.size()]));
               }
            }
        }
解决方案

the exception is thrown because you are adding/removing things from the map while you are iterating it:

dO.removeParameter(entry.getKey());
dO.addParameter(entry.getKey(),valList.toArray(new String[valList.size()]

you should use iterator.remove() instead.

这篇关于Java并发修改异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:12