Java HashMap 出现 java.util.ConcurrentModificationException 异常解决方法
java.util.ConcurrentModificationException 指的是在使用迭代器遍历集合的时候,集合的结构被修改了,导致迭代器抛出异常。
解决方法:
-
使用
ConcurrentHashMap,它是线程安全的 HashMap。 -
在遍历 HashMap 的时候,使用迭代器的
remove()方法删除元素,而不是使用 HashMap 的remove()方法。 -
在遍历 HashMap 的时候,使用
synchronized关键字同步代码块,避免多个线程同时访问 HashMap。 -
在遍历 HashMap 的时候,使用
CopyOnWriteArrayList,它是线程安全的 ArrayList。
原文地址: https://www.cveoy.top/t/topic/oKwE 著作权归作者所有。请勿转载和采集!