Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Concurrent modification exception in case of remove an item from Collection

 
Ravish Srivastava
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have seen the concurrent modification exception normally thrown if a Collection is modified while an Iterator is iterating through it.

I was able to receive concurrent modification exception when i executed below code, as i was iterating the list and was removing the item from list:

But once I commented the code to remove item from list and added a line which add a item in the list, I did not received the exception:




Does concurrent modification exception always comes when we Iterator a collection and removes an item from it? Not in case of addition .

Thanks
RS
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ravish,

Welcome to CodeRanch!

Please UseCodeTags(<-click). I've added those for this time.

Here's the thumb rule for modifying the HashMap while iterating it:
When a HashMap is being iterated by an iterator, then any addition/removal of an element must be done via iterator itself.

Currently, you are using an iterator(returned by context.keySet()) to iterate over HashMap, but using methods of HashMap to remove the element from HashMap.

If you look carefully, the ConcurrentModificationException is thrown at line which iterates over HashMap (the for loop in your code), and not at the line which removes an element from HashMap.

Also, in second piece of code, what you are actually doing is: modifying the element Key_2 (and ConcurrentModificationException is thrown only during addition/removal). Try adding a new key/value pair (e.g. context.put("key_3","value_3")) and you should get ConcurrentModificationException.

To fix this, there are two approaches:

1) Use iterator's methods to add/remove from HashMap. e.g.


2) Use ConcurrentHashMap instead of HashMap. In this case, you don't need to follow the iterator rule (that is, your current code will work without throwing ConcurrentModificationException).

I hope this helps.
 
vipul bondugula
Ranch Hand
Posts: 222
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a nice explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic