2

Why is the below exception happening?

2012-08-28 11:41:59,183 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/TFO].[tfo]] (http-0.0.0.0-8080-9) Servlet.service() for servlet tfo threw exception: java.util.ConcurrentModificationException
            at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) [:1.6.0_24]
            at java.util.HashMap$EntryIterator.next(HashMap.java:834) [:1.6.0_24]
            at java.util.HashMap$EntryIterator.next(HashMap.java:832) [:1.6.0_24]
            at net.sf.json.JSONObject._fromMap(JSONObject.java:1082) [:]
            at net.sf.json.JSONObject.fromObject(JSONObject.java:173) [:]
            at net.sf.json.JSONObject._processValue(JSONObject.java:2552) [:]
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Mallikarjuna Reddy
  • 1,212
  • 2
  • 20
  • 33

1 Answers1

10

How have you tried to remove the object (key, value) in the map? If you used the for-each Construct and tried to remove it the Exception will be thrown even if your code executes in a single-threaded environment.

If you have iterated it like this:

for(Entry<String, Object> entry : session.entrySet()) {
   if (condition) {
      // throws a ConcurrentModificationException
      session.remove(entry.getKey());
   }
}

Then you should change it to that:

Iterator<Entry<String, Object>> it = session.entrySet().iteration;
while (it.hasNext) {
   Entry<String, Object> entry = it.next(); 
   if (condition) {
      it.remove(); // avoids a ConcurrentModificationException
   }
}

Similar discussed in the question Iterate through a HashMap

Community
  • 1
  • 1
Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143