<description>&lt;p&gt;Lazily initializing fields in Java is error-prone and undermines constant-folding. JDK 26 comes with JEP 526, which previews &lt;code class= "highlighter-rouge language-plaintext"&gt;LazyConstant&lt;/code&gt;, a type that lazily initializes a value through a given &lt;code class= "highlighter-rouge language-plaintext"&gt;Supplier&lt;/code&gt;. It executes that supplier at most once successfully and then assigns the value to a field annotated with &lt;code class= "highlighter-rouge language-plaintext"&gt;@Stable&lt;/code&gt;, which allows constant folding. This API is also a poster child for how OpenJDK develops and evolves features.&lt;/p&gt;</description>

Inside Java

Chad Arimura, David Delabassee

"LazyConstants in JDK 26" [IJN]

MAR 6, 202610 MIN
Inside Java

"LazyConstants in JDK 26" [IJN]

MAR 6, 202610 MIN

Description

Lazily initializing fields in Java is error-prone and undermines constant-folding. JDK 26 comes with JEP 526, which previews LazyConstant, a type that lazily initializes a value through a given Supplier. It executes that supplier at most once successfully and then assigns the value to a field annotated with @Stable, which allows constant folding. This API is also a poster child for how OpenJDK develops and evolves features.