[英]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,尤其是针对您的案例的ConcurrentHashMap或ConcurrentSkipListMap 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.