0

I'm trying to fix a bug that occurs seldomly (a concurrentModificationException) while looping through a Set of generics Set (on the clean() method).

for (final K key : this.bean.keySet()) {
    getProxy(key).clean();
}

All the answers I found suggest to use an iterator and then calling the method remove() on it but here I am not looping through a list where I need to remove an item.

There is maybe also the possibility to convert my Set to an array and lock it (using java.util.concurrent.Locks) / make it synchronous.

I am confused about the best approach to fix my problem, the solutions above don't really satisfy me as they make me lose all benefits of multithreading.

stbr
  • 227
  • 1
  • 12
  • what does clean method do? where do you use multithreading? – voismager Oct 02 '19 at 07:53
  • This method does just a *setBean(null);* I am not experienced with Spring. The multithreading is used here I mean there is probably a few threads that try to call the clean method on the same item of the Set. – stbr Oct 02 '19 at 08:13
  • 2
    "If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined", so is your map modified anywhere else in code? – voismager Oct 02 '19 at 08:27
  • Here are the first lines of the stacktrace, I can't have it entirely as I can't reproduce the bug (you may easily understand why). I tried to debug but it really seems that the problem occurs here. – stbr Oct 02 '19 at 08:30
  • Not enough information for us to locate the problem for you. But you could debug it yourself. – Raedwald Oct 02 '19 at 08:30
  • Caused by: java.util.ConcurrentModificationException at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:394) at java.util.LinkedHashMap$KeyIterator.next(LinkedHashMap.java:405) at blablabla..clean(blablabla.java:77) – stbr Oct 02 '19 at 08:31
  • So you suggest that here I only try to access the map meanwhile it is modified somewhere else (and that I should fix the problem at this somewhere else place) ? – stbr Oct 02 '19 at 08:32
  • @Raedwald The accepted answer of your suggested question is about using an iterator and using the method remove() from it. Assuming that I find another place where an item of my list is removed. I will still have this for loop here that might not be synchronized with the current state of the Set / List or does the remove() method on an iterator "update" the status of my collection for any usage elsewhere ? – stbr Oct 02 '19 at 08:39
  • 2
    Don't just look at the accepted answer. – Raedwald Oct 02 '19 at 08:40
  • 1
    @stbr yes, that's my suggestion – voismager Oct 02 '19 at 08:49

0 Answers0