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()){

You will encounter the following runtime exception

Exception in thread “main”
at java.util.HashMap$HashIterator.nextEntry
at java.util.HashMap$

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

RSS Feed for This PostPost a Comment