This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Publication via ConcurrentHashMap

 
Onkar Joshi
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Putting a key/value into a ConcurrentHashMap does constitute safe publication for a different thread reading the map, doesn't it?

Meaning, if I change the members of an object and then put it as a value in key, value pair and then lookup the key in a different thread, I will see the updated members.

I also believe that if I do a put into the ConcurrentHashMap and then change the members of the value that was just put, there is no guarantee that a thread that does a get on the key will see the updates to the members of the value.

Wrong on any count?
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you modify the fields of an object before you put it to an instance of ConcurrentHashMap then the updated fields of that object will be visible to any thread that performs a get operation on that same map instance. If thread A performs writes, including writes to non-volatile fields or fields not guarded by a lock (i.e. synchronization) before a write to a volatile or guarded field, those writes are are guaranteed to be visible to thread B after it performs a read of the volatile / guarded field. ConcurrentHashMap can offer this happens-before visibility guarentee partly because it uses volatile variables to achieve lock-free get operations. So, as per my (limited) undertstanding, you're right on both counts, unless the field you alter modify after putting the object to the ConcurrenHashMap is declared volatile or guarded by a lock itself, of course.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic