RFR (S) 8150465: Unsafe methods to produce uninitialized arrays
Andrew Haley
aph at redhat.com
Sat Feb 27 10:24:18 UTC 2016
On 26/02/16 22:34, Jim Graham wrote:
> I think most engineers can handle "have I written to every element
> of the array" considerations, but one area where they may not have
> expertise would be in areas of how the compiler and/or processor
> cache mechanisms might reorder memory accesses in unexpected ways.
> For instance, an earlier comment showed some sort of mem-fence
> operation that was indicated to ensure that the data was written to
> the array in a thread-safe manner before any external access was
> allowed. (I'm guessing that the simple act of calling the method
> and returning the value would enforce a mem-fence in that case?)
No, it doesn't.
The Java memory model relies on dependency ordering. That is to say,
if there has been a release fence between writing the array and
storing a pointer to that array in a field Obj.f, then no other thread
will observe the uninitialized array. This is because any reader of
the data in the array must get its address via Obj.f, and all current
CPUs enforce address dependency ordering. (An address dependency
exists when the value returned by a read is used to compute the
address of a subsequent read or write.)
One other thing: it's probably not safe to use a StoreStore fence
unless the contents of the array are all constants. The reasons for
this are complex and I can provide a reference if required, but it's
probably best simply to say "use a release fence."
Andrew.
More information about the jdk9-dev
mailing list