java - 获取 java.util.ConcurrentModificationException

标签 java collections hashset

我执行了以下代码

Map<String, SyncPrimitive> syncPrimitives = new HashMap<String, SyncPrimitive>();

for (SyncPrimitive primitive : this.getSyncPrimitives()) {
         String groupId = primitive.getId();
         primitive.onConnect(groupId);
    }

然后我收到以下异常

Error while calling watcher 
java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$KeyIterator.next(HashMap.java:828)

在 onConnect 方法中,原始对象被修改。我该如何克服这个问题?

最佳答案

您无法在使用 for-each 迭代期间修改集合。如果要修改,请使用 Iterator .

这种异常描述得很清楚in documentation :

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

查看相关问题:

关于java - 获取 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852469/

相关文章:

java - 实现 JpaRepository 的最佳实践

multithreading - 具有快速元素删除和随机获取的线程安全可变集合

java - PHP 中有相当于 Java Set 的东西吗?

java - 如何从同步映射java将映射条目添加到同步/非同步映射

algorithm - HashSet 如何提供恒定时间添加操作?

java - 从 HashSet 转换为 ArrayList 时顺序丢失

Java : Implementing iterator for user-created HashSet class. next() 和 hasNext() 的语义?

java - Java/GWT 开发人员的 Flex 2D 图形学习路径?

java - 没有这样的方法错误: No virtual method setStream in class Landroid/app/WallpaperManager on older Android devices

java - 如何发现网络上 Tomcat 服务器的 IP 地址?