Null restriction on interface typed fields

Chen Liang chen.l.liang at oracle.com
Sun Jun 9 09:04:03 UTC 2024


Hello valhalla community,
In our current iteration of valhalla, we only support null restriction on value fields, as for references, null is a valid default value. Meanwhile, interfaces are not restricted to be value or identity, yet some value classes will only be represented via interfaces, most notably Map.entry().

In addition, consider this scenario in the ClassFile API: we have ClassBuilder.withMethod(xxx, Consumer<MethodBuilder>) and withMethodBody(xxx, Consumer<CodeBuilder>). A straightforward implementation of withMethodBody would be withMethod(xxx, new WithCode(cbConsumer)), where WithCode is (value) record WithCode(Consumer<CodeBuilder> build) implements Consumer<MethodBuilder>...
In this WithCode record, we can see that we are interested in declaring "build" null-restricted; if build is a value lambda that simply captures context variables, then WithCode can be inlined to the same captures should "build" be NR, without concerns about representing a null build value in the inlined form.

Another example is in Algebraic types:
sealed interface Operation permits O1, O2, ...
Record O1(Interface1 xxx)
Record O2(Interface2 xxx)
For value-based Interface1 and Interface2 values, we might seek to NR the fields so the record representations can be simpler.

Thus, I recommend considering support for NR on interface fields in addition to on explicit value type fields. Though this might lead down to the rabbit hole of "heap pollution of null on reference pointers", I still believe its benefit outweighs its cost, especially in cases where these values can be restricted on the stack in escape analysis, as in most functional APIs (function only invoked conditionally, function objects not stored when method exits).

Chen Liang

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/valhalla-dev/attachments/20240609/00f007ca/attachment.htm>


More information about the valhalla-dev mailing list