[concurrency-interest] Explicitly initializing volatile fields with default values

thurstonn thurston at nomagicsoftware.com
Fri Dec 18 13:26:47 EST 2015

Aleksey Shipilev-2 wrote
> On 12/18/2015 04:30 AM, thurstonn wrote:
>> class B
>> {
>>     int f = 42;
>>     boolean initialized = true;
>>     volatile int v = 0;
>> }
>> B global;
>> Thread 1:
>>    global = new B();
>>  Thread 2:
>>    B b = global;
>>    if (b != null && b.initialized && b.v == 0) {
>>      print(b.f); // ?
>>    } 
>> I still think that the JMM allows either 0 or 42.
> Yes, it does. I don't see how this case differs from the original case
> without the "initialized" field. Moreover, since the $initialized read
> is done before "acquiring" $v read, there is no effect whatsoever ;)

The order of the $initialized read wrt to the $v read is irrelevant to the
point I was making, i.e. if the code was:

if (b != null && b.v == 0 && b.initialized) 
      print(b.f); // ?
the point would be the same.
Why?  because we're in agreement that no synchronizes-with edge can be
deduced from the program, so in terms of the JMM (which is what I meant by
<r(initialized), T2, true> tells you nothing about 
<r(f), T2, ?>

But in reference to definition of "safe" (#2 below) compare:

1.  Elide the initializing write of $v
2.  There is some store fence emitted between the initializing write to
$initialized = true and $v=0

I was merely positing on some platform(s),
in case 1 ==>
<r(initialized), T2, true> tells you nothing about 
<r(f), T2, ?>

but in case 2 ==>
<r(initialized), T2, true> always results in:
<r(f), T2, 42>

again, not as dictated by the JMM, but by a particular platform's
implementation/behavior of the JMM; producing a stronger memory model than

If such a platform exists, then eliding the initializing $v = 0, hence
eliding the store fence (#1 above), changes the possible results of program
executions (which would be "unsafe" in the sense of #2 below)

> "There is a gut feeling that removing these initializations is *safe*"
> But partly it comes down to your definition of "safe", i.e.
> 1.  Safe ==> spec-compliant
> or
> 2.  Safe ==> no JVM presently in use will behave differently in the face
> of
> initialization-to-default-value elision

I tried to frame a more formal question in the original note:

"Is there a plausible case that shows the semantical difference with
field initializer storing a default value, and without one, that does
*not* also affect single-threaded usages (i.e. it does not follow from
the instance initialization sequence itself)?"

The answer to which is, apparently, "no".


Concurrency-interest mailing list
Concurrency-interest at .oswego

signature.asc (836 bytes)

View this message in context: http://jsr166-concurrency.10961.n7.nabble.com/Explicitly-initializing-volatile-fields-with-default-values-tp13093p13104.html
Sent from the JSR166 Concurrency mailing list archive at Nabble.com.

More information about the Concurrency-interest mailing list