ConcurrentModificationException 的解决办法

1.出现 java.util.ConcurrentModificationException 时的解决办法

//(1) 根据某个id直接删除全部(如果数据库中的多对多关系)
Set<Largess> largessSet = promotion.getLargess();
largessSet.clear();
//或者
for(Iterator it = largessSet.iterator();it.hasNext();) {
Largess largess = (Largess)it.next();
it.remove();//先移除
largessSet.remove(largess);
}
//(2) 根据某个条件删除 就是用Iterator
for(Iterator it = promotionList.iterator();it.hasNext();) {
Promotion promotion = (Promotion)it.next();
it.remove();//先移除
if(promotion.getEndTime().before(new Date())) {
xxxManager.remove(promotion);
//TODO 其他处理
}
}
ConcurrentModificationExceptionJava中的一个异常类,当在迭代集合的过程中,如果同时对集合进行修改操作,就会抛出该异常。\[2\]这个异常的出现是因为在迭代过程中,集合的结构发生了改变,导致迭代器无法正确地访问集合的元素。\[3\]在Java中,集合类通常会维护一个modCount变量,用于记录集合的修改次数。当调用next()方法时,会调用checkForComodification()方法来判断modCount是否与预期的修改次数(expectedModCount)相等,如果不相等就会抛出ConcurrentModificationException异常。\[1\] 为了避免出现ConcurrentModificationException异常,可以采取以下几种解决办法: 1. 使用Iterator的remove()方法来删除元素,而不是直接使用集合的remove()方法。 2. 使用并发集合类,如ConcurrentHashMap或CopyOnWriteArrayList,它们提供了线程安全的迭代器。 3. 在迭代过程中,将需要修改集合的操作放在一个synchronized块中,以确保同一时间只有一个线程在修改集合。 总之,ConcurrentModificationException异常的出现是因为在迭代集合的过程中,同时对集合进行了修改操作。为了避免这个异常,可以采取上述的解决办法。 #### 引用[.reference_title] - *1* *3* [ConcurrentModificationException异常](https://blog.youkuaiyun.com/Jiangshan11/article/details/83038857)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [为什么会出现ConcurrentModificationException异常,如何解决?](https://blog.youkuaiyun.com/sl1202/article/details/108112274)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值