Java concurrent modification exception

后端 未结 4 900
南笙
南笙 2021-01-21 08:24

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 obj

相关标签:
4条回答
  • 2021-01-21 08:48

    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.

    0 讨论(0)
  • 2021-01-21 08:50

    Not sure you need to alter the keys of Map, it appears all you want to do is alter the values in the arrays.

    for(String[] values: dO.getParameterMap().values()) 
        for (int i = 0; i < values.length; i++) 
            values[i] = escapeHTML(values[i]);
    

    I would make sure the Map does have null values stored. But if you can't change this you will need to add if(values != null)

    0 讨论(0)
  • 2021-01-21 09:04

    You should remove/add only if you are changing a key in a map. As I see in the code, you are changing only value. Hence you could use entry.setValue(...) instead.

    0 讨论(0)
  • 2021-01-21 09:11

    ConcurrentModificationException is thrown when you use fail-fast iterators (eg: entries.iterator() is fail-fast iterator). What they do is they iterate over original collection object. To be able to modify and iterate over a collection object you can use fail-safe iterator (eg: List<Book> books = new CopyOnWriteArrayList<>()) This will take a copy inside memory while iterating over the elements and even you will be able to modify it.

    0 讨论(0)
提交回复
热议问题