• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronized and Map  RSS feed

 
Prabjhot Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




> ConcurrentHashMap is thread-safe for write operations, but still there could be data issue (during time taken for conditions check or other code) with multiple requests .



>>> if I change above code to following, then it does not make difference if I use HashMap, HashTable or ConcurrentHashMap..
I am confused and would appreciate more info / suggestion...














 
Knute Snortum
Sheriff
Posts: 4270
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are you confused about specifically?
 
Prabjhot Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your reply ....
Knute Snortum wrote:What are you confused about specifically?


If I use 1st block of code without synchronized, then there could be data issue,

if I use 2nd block of code with synchronized, then HashMap, HashTable, ConcurrentHashMap would have same performance as locking is at Map instance level, then why we have HashMap, HashTable, ConcurrentHashMap or Collections.synchronizedMap(Map<k,v>) ?


 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prabjhot Singh wrote:If I use 1st block of code without synchronized, then there could be data issue,
if I use 2nd block of code with synchronized, then [Map] would have same performance as locking is at Map instance level, then why we have HashMap, [etc] or Collections.synchronizedMap(Map<k,v>) ?

For precisely the reason you stated in the first part of your post.

You can have "safe", or you can have "fast", but NOT both ... at least not at the same time. And synchronization is generally only a lot slower in cases of high contention.

ConcurrentHashMap (from what I understand) attempts to be somewhere between the two, and is designed specifically for cases of high contention. It is write-consistent, and weakly read-consistent, and it achieves this without "whole structure" locking - at least for the most part.

I suspect you're worrying about stuff that isn't in fact an issue if you use CHM; but without knowing what your exact requirements are, it's difficult to say.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!