How to avoid ConcurrentModificationException when iterating over a map and changing values?

前端 未结 7 1014
眼角桃花
眼角桃花 2020-12-06 09:46

I\'ve got a map containing some keys (Strings) and values (POJOs)

I want to iterate through this map and alter some of the data in the POJO.

The current code

7条回答
  •  北海茫月
    2020-12-06 10:24

    In order to provide a proper answer, you should explain a bit more, what you are trying to achieve.

    Still, some (possibly useful) advice:

    • make your POJOs thread-safe and do data updates on POJOs directly. Then you do not need to manipulate the map.
    • use ConcurrentHashMap
    • keep on using simple HashMap, but build a new map on each modification and switch maps behind the scenes (synchronizing the switch operation or using AtomicReference)

    Which approach is best depends heavily on your application, it is difficult to give you any "best practice". As always, make your own benchmark with realistic data.

提交回复
热议问题