RFR (S) 8150465: Unsafe methods to produce uninitialized arrays

Aleksey Shipilev aleksey.shipilev at oracle.com
Thu Feb 25 14:36:19 UTC 2016


On 02/25/2016 05:13 PM, Andrew Haley wrote:
> On 02/25/2016 01:44 PM, Aleksey Shipilev wrote:
>> Of course, you will still see garbage data if after storing the array
>> elements into the uninitialized array you would publish it racily. But
>> the same is true for the "regular" allocations and subsequent writes.
>> The only difference is whether you see "real" garbage, or some
>> "synthetic" garbage like zeros. It is, of course, a caller
>> responsibility to publish array safely in both cases, if garbage is
>> unwanted.
> 
> Of course, my worry with this optimization assumes that programmers
> make mistakes.  But you did say "complicated processing is done after
> the allocation."  And that's where programmers make mistakes.

Of course they do; at least half of the Unsafe methods is suitable for
shooting oneself in a foot in creative ways. Unsafe is a sharp tool, and
Unsafe callers are trusted in their madness. This is not your average
Joe's use case, for sure.

In other words, callers can and should provide defense in depth when
they are using Unsafe. It's not the goal for Unsafe to provide those
defenses, if that contradicts performance goals. If you need defenses,
code in plain Java.

E.g. for suggested use in StringConcatFactory [1], we say:
"StringConcatFactory would probably have to provide a few more checks if
using any new Unsafe API: notably the "exactness" debug check in
MH_INLINE_SIZED_EXACT should probably be turned on by default -- this
will check we never ever construct a String with garbage data." This
single index check is much cheaper than defensively zeroing the entire
array.

Thanks,
-Aleksey

[1] https://bugs.openjdk.java.net/browse/JDK-8150463



More information about the jdk9-dev mailing list