Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1331
  • Last Modified:

HashMap ConcurrentModificationException

Hi,

What is wrong with my code here?

  private HashMap mappings;

  private void prune() {
    // for every mapping in mappings
    Iterator it = mappings.keySet().iterator();
    while (it.hasNext()) { // for every mapping
      String key = (String) it.next();
      Object o = mappings.get(key);
      if (!(o instanceof ArrayList)) // if not an ArrayList
        mappings.remove(key); // delete mapping
    }
  }

java.util.ConcurrentModificationException
      at java.util.HashMap$HashIterator.nextEntry(HashMap.java:762)
      at java.util.HashMap$KeyIterator.next(HashMap.java:798)
      at com.test.MappingsGrid.prune(MappingsGrid.java:73)
0
ycomp
Asked:
ycomp
1 Solution
 
petmagdyCommented:
how do u run this code?
anyway try:
      if (!(o instanceof ArrayList)) // if not an ArrayList
        synchronized(mappings)
{
        mappings.remove(key); // delete mapping
}
........
0
 
objectsCommented:
>        mappings.remove(key); // delete mapping

that should be:

it.remove();
0
 
objectsCommented:
you cannot delete entries directly from the map while you are iterating thru it
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
CEHJCommented:
If more than one thread is involved, create your Map thus:

Map synchMappings = Collections.synchronizedMap(mappings);

and then operate on 'synchMappings'
0
 
ycompAuthor Commented:
sorry.. forgot to say it is a single thread.

objects: that's what I was thinking... any ideas how I should do what I want to do.. i.e. delete those mappings w/o throwing an exception?
0
 
ycompAuthor Commented:
objects: sorry I should read more carefully next time.. I'll check out it.remove()
0
 
objectsCommented:
:)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now