OpenJDK plan would add computed constants to Java

Computed constants offer the performance and safety benefits of final fields, but greater flexibility in the timing of initialization, the proposal states.

shutterstock 560673883 coffee poured into white coffee cup coffee beans java
jazz3311 / Shutterstock

An OpenJDK proposal would introduce computed constants to Java. Immutable value holders that are initialized at most once, computed constants offer the performance and safety benefits of final fields while offering more flexibility as to the timing of initialization.

The proposal is currently in a draft status and eyed for standard Java. Driving the effort is the notion that developers should “prefer immutability,” because immutability confers a number of advantages. Immutable objects can only be in one state, which is carefully controlled by its constructor. Immutable objects can be freely shared with untrusted code. And immutability enables all manner of runtime optimizations.

Java’s main tool for managing immutability is final fields, but final fields have restrictions. As a result, developers must choose between the benefits of finality and flexibility in timing of initialization. Developers have devised strategies to ameliorate the imbalance, but none are ideal.

The computed constants API defines classes and an interface so client code in applications and libraries can perform tasks including defining and using computed constant objects and constant collections. The API resides in the java.lang package of the java.base module.

Goals of the plan include:

  • Decoupling initialization of computed constants from the initialization of their containing object or class.
  • Providing an intuitive API for computed constants and collections.
  • Enabling constant folding optimizations for computed constants and supporting dataflow dependencies between these constants.
  • Reducing the amount of static initializer code and/or field initialization to be executed.
  • Allowing disentanglement of the “soup” of <clinit> dependencies by applying the above.
  • Upholding consistency and integrity, even in a multi-threaded environment.

Non-goals include providing additional language support for expressing constant computation and preventing or deprecating existing idioms for expressing lazy initialization.

With the feature set for the next version of standard Java, Java Development Kit 21, now frozen, with the release due in September, the earliest possible version of standard Java that could include computed constants would be JDK 22, due in March 2024.

Copyright © 2023 IDG Communications, Inc.

InfoWorld Technology of the Year Awards 2023. Now open for entries!