简体   繁体   English

在这种情况下如何避免 ConcurrentModificationException?

[英]How to Avoid ConcurrentModificationException in that case?

I understand that when I try to modify (add in that case) the list I got ConcurrentModificationException, but what is the best solution to fix that?我知道当我尝试修改(在这种情况下添加)列表时,我得到了 ConcurrentModificationException,但是解决这个问题的最佳解决方案是什么?

for (Map.Entry<String, Child> entry : children.entrySet() {
     childEvent.child = entry.getValue();
     if (childEvent.getDate() != null && childEvent.getDate().equals(selectedDate)) {
         if(this.selectedDayevents.isEmpty()) {
             // List                                
             this.selectedDayevents.add(childEvent);
          }
         for (CareDay selectedCareDay : this.selectedDayevents) {
             // Here I have to combine data in some cases...
         }
     }  
}

One simple way around this problem is to iterate over a copy of the entry set:解决此问题的一种简单方法是遍历条目集的副本

for (Map.Entry<String, Child> entry : new HashSet<>(children.entrySet())) {
    // same code
}

If your map is not too big and you're not doing it very often, you won't notice a difference in performance.如果您的 map 不是太大并且您不经常这样做,您将不会注意到性能差异。

If your requirement is to enable concurrent access to the collection, then you should explore java concurrency APIs and especially ConcurrentHashMap or ConcurrentSkipListMap for your case.如果您的要求是启用对集合的并发访问,那么您应该探索 java 并发 API,尤其是针对您的案例的ConcurrentHashMapConcurrentSkipListMap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何避免一次监听的情况下发生ConcurrentModificationException - how to avoid ConcurrentModificationException for listen once listener case 在这种情况下如何处理ConcurrentModificationException - How to deal with ConcurrentModificationException in this case 添加 ArrayList 元素时如何避免“ConcurrentModificationException”? - How to avoid "ConcurrentModificationException" while add ArrayList elements? 如何避免 java.util.ConcurrentModificationException - How to avoid java.util.ConcurrentModificationException 迭代此集合时如何避免ConcurrentModificationException? - How to avoid ConcurrentModificationException while iterating this collection? 如何在多线程代码中避免ConcurrentModificationException - How to avoid ConcurrentModificationException in multi-threaded code 避免Iterator ConcurrentModificationException的方法 - Ways to avoid Iterator ConcurrentModificationException 从 ArrayLists 中删除对象时如何避免 concurrentModificationException” - how to avoid concurrentModificationException when removing an object from to ArrayLists" 如何在并发线程中操作`values()`和`put()`时避免使用HashMap“ConcurrentModificationException”? - How to avoid HashMap “ConcurrentModificationException” while manipulating `values()` and `put()` in concurrent threads? 从ArrayList中删除对象时如何避免ConcurrentModificationException - How to avoid a ConcurrentModificationException when removing objects from an ArrayList
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM