RSS Feed for This PostCurrent Article

Java Concurrent Modification Exception

I was troubleshooting a multi-threaded application for a occasional exception. Run the following code

public static void main(String[] args){
    Map<String,String> context = 
             new HashMap<String,String>(1);

    context.put("key_1", "value_1");
    context.put("key_2", "value_2");

    for (String key: context.keySet()){
        System.out.println(context.get(key));
        context.remove(key);
    }
}

You will encounter the following runtime exception

Exception in thread "main" 
 java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry
(HashMap.java:841)
at java.util.HashMap$KeyIterator.next(HashMap.java:877)
    

I am not going to details here. Suffice to say that you can not access a Collection and modify it at the same time.  This will also happen in if your application is multi-threaded and there is concurrent access to the Map.


Trackback URL


Sorry, comments for this entry are closed at this time.