Reference favoring primitive class heap allocations

Stig Rohde Døssing stigdoessing at gmail.com
Wed Sep 1 10:43:46 UTC 2021


Hi,

JEP 401 describes that current value-based classes will be made reference
favoring to avoid breaking existing code. Optional is one of these. I'm
trying to understand the impact this will have on existing APIs with
respect to heap allocation.

Please assume for the following code snippets that ordinary scalar
replacement does not apply.

As I understand it, code like

Optional.val of(T item) { new Optional.val(item) }
Optional.val<String> s = of("Hello")

would tell the JVM that the Optional does not necessarily have to go on the
heap, but could maybe go on the stack or in registers instead.

When "of" is instead defined with the reference type, as in

Optional of(T item) { new Optional(item) }
Optional.val<String> s = of("Hello")

will the Optional always go on the heap?

Also is the plan to be able to avoid the heap for return values, or will
the return value of

Optional.val of(T item)

always go on the heap unless "of" happens to be inlined?

Thanks for reading.


More information about the valhalla-dev mailing list