File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Publication via ConcurrentHashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Publication via ConcurrentHashMap" Watch "Publication via ConcurrentHashMap" New topic

Publication via ConcurrentHashMap

Onkar Joshi
Ranch Hand

Joined: Mar 01, 2007
Posts: 116
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?

SCJP 5 - 95% | SCWCD 1.4 - 88% | SCBCD 5 - 93%
Onkar Joshi's blog | LinkedIn profile
Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

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.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
I agree. Here's the link:
subject: Publication via ConcurrentHashMap
It's not a secret anymore!