[concurrency-interest] Visibility of array initialization (Raph Frank)

Vladimir Sitnikov sitnikov.vladimir at gmail.com
Sun Aug 12 16:36:37 EDT 2018


Valentin>Having said that, the anwser to your question "Is it possible for
the 2nd thread to print zero?  Is it guaranteed to print -1 or 2?" is: The
second thread is allowed to print either -1 or 3 and nothing else (NPE is
also not allowed).

I would argue there.

TL;DR: -1, 0, 3 are allowed. NPE is forbidden.


1) NPE is not allowed (since there's only one write of null to `array`
field which is implicit write of default value).

2) 0 is also allowed since Thread 2 could see updated value of `array`
(that is it could see the reference to the array that was set after the
thread started).
Apparently, there are "implicit writes of 0 values of the elements in the
new array", and nothing prevents Thread 2 from observing those writes.

I'm not a lawyer, but
https://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.10.1
seems to address that:

JLS6> and each component of the array is initialized to its default value
(ยง4.12.5).

In other words, new int[] {1, 2, 3}; does not mean the array is created
"atomically".
It is equivalent to the   x=new int[3]; x[0]=1; x[1]=2; x[2]=3;
Obviously that can cause Thread2 to observe 0 as well.


Vladimir
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20180812/fffb8bf5/attachment.html>


More information about the Concurrency-interest mailing list