I have a superclass A which has a TreeMap needed to be accessed by A subclass when an event it fired (an unsubscribe notification), there are 4 objects of class B instantiated. However I get ConcurrentModificationException when all the classes access it, Im guessing this is because they are all trying to access the same A.x TreeMap.
Each subclass of A should have its own local copy of the TreeMap, is there anyway to declare this in A or do all subclasses have to declare it so there is no ConcurrentModificationException.
Theres more code than that but that is all the is resulting in throwing the exception, its not threaded so they aren't accessing the same variable in different threads. The only way I can see it happening is through inheritance.
I assume that the code that calls somefunction is passing in x.
Is the body of the loop doing anything to modify the TreeMap (or the pubKeys set)? The forEach loop uses the set's iterator, which will throw an exception on the NEXT use of the iterator after a change to the underlying collection, if the change is not made through the iterator - from TreeMap javadoc:
if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
Since you are using a forEach loop, you don't actually have access to the iterator it is using, so any changes you make to the collection will by definition not be through the iterator's remove method. Since it is the iterator that throws the exception, it will not be thrown until the next use of it, which is why the exception occurs on the forEach line, rather than within the body of the loop.
posted 10 years ago
Thanks thats sorted it, rather than the forEach loop, I sent it to an Array and used that.
Thanks for all your help.
I have always wanted to have a neighbor just like you - Fred Rogers. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop