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

Aleksey Shipilev aleksey.shipilev at oracle.com
Fri Dec 18 06:56:49 EST 2015


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 ;)


> "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".

Thanks,
-Aleksey


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20151218/10aac8b2/attachment.bin>


More information about the Concurrency-interest mailing list