Another kind of ConcurrentModificationException, how can I solve it?



In my application, I will iterate a map and send out a message to
another class with the key of current object to which iterator is
pointing. And the operation is in the same thread. This class get the
notification will do more handle and then, it will try to remove this
object from the map with the key.
But when I try to go on to the next object in the map, I will get the
ConcurrentModificationException.

I know if I call Iterator.remove during iterating, no exception will
happen. But I can't do that, as I must ensure the other class has
completely handled the notification.

// OK, but not what I want
Map<Integer, String> sessions = plugin.getSessions();
Set<Map.Entry<Integer, String>> set = sessions.entrySet();
for (Iterator<Map.Entry<Integer, String>> it = set.iterator();
it.hasNext();) {
// send out notification...
it.remove();
}

// Failed
Map<Integer, String> sessions = plugin.getSessions();
Set<Map.Entry<Integer, String>> set = sessions.entrySet();
for (Iterator<Map.Entry<Integer, String>> it = set.iterator();
it.hasNext();) {
// send out notification...
}

// in another class, after check and handle the notification. If
failed, should not release resource.
void release(int key) {
Map<Integer, String> sessions =
((MockManagedPlugin)plugin).getSessions();
sessions.remove(key);
}

Do you have any suggestion to me about this issue?
.



Relevant Pages

  • Riemann surface for iteration of complex map?
    ... I once had a thread here where I mentioned the idea of using a Riemann ... surface to "continuously iterate" a complex map: ... real and theta any real. ...
    (sci.math)
  • Re: use remove_if in map
    ... RemoveInvalid(std::setvalidset) ... valid map elements into another map (possibly via a vector, ... log m) where s is the size of the valid set, and m that of the map. ... Option 2 is to iterate over the map and check each element for validity. ...
    (microsoft.public.vc.stl)
  • Why is not "sub" necessary? What is the difference: block and expression?
    ... I'm trying to understand the map function in perl and have been studying ... When David calls his iterate function, why does he not need to use the ... keyword "sub"? ...
    (perl.beginners)
  • Re: Collection
    ... The purpose of a Map is to hold associations; using a Map as a List is overkill. ... If, OTOH, you do need the associative lookup and only occasionally need to loop through the entrySet, then just iterate over the entrySet. ... It is unlikely that you actually need both Mapness and sortedness. ...
    (comp.lang.java.programmer)
  • Re: do u know ramanujan numbers algorithm
    ... You could also iterate only over two variables and save the values ... Before actually adding it to the map, ... keys in the map that are small enough that re-encountering them ... Any one else interested pay me $200 for the solution. ...
    (comp.lang.java.programmer)