• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Concurrency: why this snippet throws a ConcurrentModificationException?

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm in the chapter Concurrency of OCP study guide, and I saw this snipped:



This throws a ConcurrentModificationException.
Changing the instance type from HashMap to ConcurrentHashMap fix the problem, but it was not clear enough for me why the snippet throws that exception.
Any explanation will be welcome

Thanks in advance
 
Sheriff
Posts: 15784
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Google is your friend in these situations: HashMap ConcurrentModificationException
 
Ranch Hand
Posts: 84
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thiago Medeiros wrote:I'm in the chapter Concurrency of OCP study guide, and I saw this snipped:



This throws a ConcurrentModificationException.
Changing the instance type from HashMap to ConcurrentHashMap fix the problem, but it was not clear enough for me why the snippet throws that exception.
Any explanation will be welcome

Thanks in advance

you can use basic for loop that does not throw exception any hope it helps
 
Saloon Keeper
Posts: 12142
258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If by basic for-loop you mean using an index, that's generally not the appropriate solution. The basic for loop should be avoided unless you need to operate on multiple arrays at the same time.

If you really must modify a collection while you're iterating over it (as opposed to say, modifying a copy of the collection and replacing the original with the copy after the loop is finished), then use an Iterator. The loop in the original post can be written like this:
 
Bartender
Posts: 4001
156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since keyset() is a view of the keys in a map, it can be a little shorter:
 
What is that? Is that a mongol hoarde? Can we fend them off with this tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic