[concurrency-interest] Re: reordering around volatiles (fwd)

matthias.ernst@coremedia.com matthias.ernst@coremedia.com
Mon, 15 Dec 2003 19:41:17 +0100 (CET)


I had a similar question a while ago and got an answer from Bill
Pugh. Reading/Writing volatiles does constitute a memory barrier in the
revised memory model. Please see below.

I actually remember that Hotspot 1.4.1 or 1.4.2 actually should already
implement this behaviour. I forgot the source. Your findings seem to
contradict.

Please see below.

-- 
Matthias Ernst
CoreMedia - Smart Content Technology

"Overall, JAXP is much like the rest of Java: a partial description
intended to assist developers in using a single implementation"

---------- Forwarded message ----------
Date: Tue, 19 Aug 2003 14:48:06 -0400
From: Bill Pugh <pugh@cs.umd.edu>
To: matthias.ernst@coremedia.com
Cc: jsr-133-eg@jcp.org
Subject: Re: reordering around volatiles

Matthias,
   Double-checked locking does indeed allow double-checked locking to work.

   If thread t1 writes to a volatile variable v, and thread t2 reads
that volatile and sees the value written by thread t1, it establishes
a happens-before relationship from t1 to t2. In particular, any
writes performed by t1 before it writes to the volatile are
guaranteed to be visible to any reads by thread t2 after it reads
that volatile.

The code you gave for currentCache works fine, although if multiple
threads are updating the cache without other synchronization, updates
could be lost. The other thing you should be aware of is that the new
JSR-166 concurrency libraries will contain a ConcurrentHashMap that
should suit your needs well. It doesn't require any locks for reading
(internally, it uses volatiles) and offers very high performance. See
the following javadoc for more information.
	http://gee.cs.oswego.edu/dl/concurrent/dist/docs/java/util/concurrent/ConcurrentHashMap.html

Bill Pugh

>Hi,
>
>the verdict on "Double-checked Locking"
>(http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)
>predicts DCL to be correct under the proposed model when using a volatile
>object reference (see bottom of page, "Under the proposed Java Memory
>Model / Fixing Double-Checked Locking using Volatile").
>
>I cannot seem to derive that from the review specification. Is it correct
>to use a volatile here ? Actually, I want to atomically exchange an object
>reference for another but that seems equivalent:
>
>volatile HashMap currentCache;
>
>read:
>   currentCache.get(key)
>   ...
>
>write:
>   HashMap newCurrentCache = new HashMap(currentCache).withNewValue()
>   currentCache = newCurrentCache
>
>
>
>Regards
>Matthias
>--
>Matthias Ernst
>Software Engineer