gpt4 book ai didi

java - 向 hashmap 添加值时出现 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-02 05:13:26 25 4
gpt4 key购买 nike

下面的代码在两个线程访问同一个线程时收到并发修改异常。

我想知道是否

  1. 如果使用并发Hashmap是否可以避免这个异常。
  2. 如果我们使用并发 hashmap 在多线程环境中会出现任何问题。

或者有其他方法可以防止这种异常吗?

我不打算使用同步,因为此代码是在轮询期间使用的。因为一个线程可能必须等待另一个线程完成执行。

代码是

HashMap<Integer, myModel> aServiceHash = new HashMap<Integer, myModel>();
HashMap<Integer, myModel> rServiceHash = new HashMap<Integer, myModel>();

for (myModel ser : serAccepted){
aServiceHash.put(service.getOriginalDate(), ser);
}
for (myModel ser : serRequested) {
if (aServiceHash.containsKey(service.getDate())) {
aServiceHash.put(serv.getDate(), serv);
}
else
rServiceHash.put(service.getDate(), ser);
}

引用http://examples.javacodegeeks.com/java-basics/exceptions/java-util-concurrentmodificationexception-how-to-handle-concurrent-modification-exception/

http://www.journaldev.com/378/how-to-avoid-concurrentmodificationexception-when-using-an-iterator

How to avoid HashMap "ConcurrentModificationException" while manipulating `values()` and `put()` in concurrent threads?

使用 JSF 2.1、JDK 7.1。

最佳答案

HashMap 不是线程安全的。 ConcurrentHashMap是线程安全的。当从不同线程访问映射时,为了线程安全,最好是并发的。

是的,它将避免异常。从这个方向不会出现多线程问题。您仍然需要确保没有线程删除您稍后打算使用的内容。

防止异常的另一种方法是在每次插入之前锁定映射,无论是通过同步块(synchronized block)还是 Lock 对象。

关于java - 向 hashmap 添加值时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27168330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com