[concurrency-interest] ConcurrentHashMap: HashEntry.value potentially null to readers comment

Dawid Weiss dawid.weiss at gmail.com
Mon Jun 20 07:02:42 EDT 2011

Hello everyone,

The questions concerning safe publication, final fields and visibility
pop up from time to time and I have tracked the list's archives, but
couldn't find an appropriate answer. So here is the question we have
been discussing with a friend of mine:

ConcurrentHashMap.HashEntry has the following fields:

        final K key;
        final int hash;
        volatile V value;
        final HashEntry<K,V> next;

the only constructor assigns them in this order:

            this.key = key;
            this.hash = hash;
            this.next = next;
            this.value = value;

it is clear to us that all final fields will be published safely; the
comment in that class states that:

     * Because the value field is volatile, not final, it is legal wrt
     * the Java Memory Model for an unsynchronized reader to see null

QUESTION 1. The first question is for the possible rationale of
publishing a reference to a partially constructed object to memory. As
compiler writers does anybody know when would such an optimization be
speeding up things or be at all advisable? Or is it just protecting
oneself against JMM memory model scenario that hardly ever takes place
in the real generated code (as actually stated in the comment to

QUESTION 2. Would the above scenario change if we reordered
assignments so that volatile variable is assigned first (before final
fields)? As in here:

            this.value = value;
            this.key = key;
            this.hash = hash;
            this.next = next;

It is my understanding that final field assignments must precede the
publication of the object's reference; is this freely reorderable with
respect to volatile writes?

QUESTION 3. This one is about assignment piggybacking using volatiles.
If we had a hardware architecture that would allow selective cache
flushes (to single-cell memory addresses, for example), must writing
to a volatile enforce a flush of all of the thread's caches? Really?
If so the only "gain" over full monitors is no need for thread locking
(only a cache flush), right? I don't see the JLS stating such a thing,
but I admit the section about happens-before algebra is pretty dense
to me.

Thanks in advance for all the help or pointers to relevant discussion elsewhere.


More information about the Concurrency-interest mailing list