Re: JavaMemoryModel: Question about the semantics of volatile

From: Jeremy Manson (
Date: Thu Mar 18 2004 - 14:49:39 EST

Thomas Wang wrote:

>>Initially x == y == v == v2 == 0, x and y non-volatile, v and v2
>>Thread 1:
>>Thread 2:
>>Then r1==r3==1 becomes possible with the strong and weak
>How? v=0 has a release fence, and r2=v has an acquire fence, ending up
>as a full fence. Same for v2=0; r4=v2;
>Certainly you cannot perform r2=v until v=0 has been performed.

One of the properties that we have long since decided is desirable for the
JMM is that thread- local synchronization actions have no effect across
threads. So the compiler can detect that v and v2 are only accessed in a
single thread, and treat them as normal variables.

In fact, because the read of v2 will always return 0, you can even perform
r2 = v before v = 0!

In general, there is no abstract notion of a "main memory" to which you
can perform a "flush". You can only reason about what actions must appear
to happen before what other actions.

>>>I also believe volatile variables preventing compile time
>>>code motion is
>>>a good idea, for the same reason.
>>Again, it is a myth that volatile variables prevent compile time code
>>motion. They prevent it some of the time but not all of the time. To figure
>>out when they do or do not prevent it, we have to reason about the
>>happens-before relation.
>Hmm, so you say we can re-order the volatiles, if we know they do not
> v = new Integer(0); // v is volatile Integer
> String x = v2; // v2 is volatile String; v and v2 do not alias
> // can loading v2 happen prior to storing to v?

You can reorder them if they are thread-local. But we guarantee
sequential consistency if your program consists of only volatiles.
Another thread could have

v2 = new String("foo");
Integer i = v;

You wouldn't be able to get the result x = null, i = null.

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:00 EDT