Can @Stable (or something similar) be made accessible?

Vladimir Ivanov vladimir.x.ivanov at
Fri Jan 12 12:50:02 UTC 2018

>> Would you be so kind to explain how this breakage occurs? I can
>> understand that improper use of @Stable annotation may break the
>> intended semantics of a program, but to break the integrity of VM? I'm
>> trying to imagine the scenario, but can't.
> One example might be a @Stable array field used with a constant index to
> write a value into it.  If the JIT trusts the field to be final it could
> elide a range check when storing into the slot.  If the field is actually
> modified to be a smaller length array, you’d end up with a write to an out
> of bounds memory area.
> I suppose something similar can be done with a non-array field - make the
> field type Object, store a Foo initially.  The JIT can assume the type is
> always Foo and generate read/writes using its layout.  Then change the
> field to another type.

No, it doesn't work that way. @Stable enables JIT to constant fold loads 
from fields/arrays (holding non-default values) whenever possible. After 
that JIT has a constant value at its hands. All other optimizations 
follows from that: range check before array store can be elided since 
array instance is known and its length is known as well, type check can 
be elided since constant type is known. But the value won't be reloaded 
from memory, all optimizations happen on a constant which was loaded 
from memory once during compilation.

So, the worst case scenario is: a value written into @Stable field/array 
  is never visible in some code no matter what you do. It can lead to 
nasty bugs when different parts of program don't agree on observed 
value. It can happen when user doesn't obey @Stable contract and 
performs multiple writes into a @Stable field/array. Current 
implementation in HotSpot doesn't forbid that.

Best regards,
Vladimir Ivanov

More information about the core-libs-dev mailing list