• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashMap  RSS feed

 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a class which uses HashMap internally to store its data. I have 3 methods in the class - add(), get() and exists(). If this class were to be accessed from a multi-threading environment, should I synchronize all 3 methods?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

The basic rule is that any time you have shared data, all access to that data must be protected.
 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Jeff. So, is the reasoning behind this the fact that a thread could add an object to the map at the same time another thread is using the exists() method?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's one scenario that could cause problems, yes. But really any case where 2 or more threads are accessing the shared data and at least one of them is writing it is a potential problem.
 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!