java.util.ConcurrentModificationException 解决办法

在使用iterator.hasNext()操作迭代器的时候,如果此时迭代的对象发生改变,比如插入了新数据,或者有数据被删除。
则使用会报以下异常:
Java.util.ConcurrentModificationException

解决办法:

  1. 通过Iterator修改Hashtable

    while(it.hasNext()) {
               Object ele = it.next();
         it.remove();
     }
    
  2. 根据实际程序,您自己手动给Iterator遍历的那段程序加锁,给修改HashMap的那段程序加锁。

  3. 使用“ConcurrentHashMap”替换HashMap,ConcurrentHashMap会自己检查修改操作,对其加锁,也可针对插入操作。
    import java.util.concurrent.*;

原文地址:https://www.cnblogs.com/zhousiwei/p/10625716.html