Hi Ryan, is there a use case where people call getEnumConstants() and access a 
fixed index of array element?

This is so far the only use case I can think of that would be negatively 
impacted by the lack of constant folding for this method.

In addition, I do not recommend adding more @Stable - we should consider better 
representations like LazyConstant.

Regards
________________________________
From: core-libs-dev <[email protected]> on behalf of Ryan Hallock 
<[email protected]>
Sent: Thursday, February 12, 2026 3:45 PM
To: [email protected] <[email protected]>
Subject: Add @Stable to Class#enumConstants.

Hello, I am new to OpenJDK development and I want to propose changes to 
Class#enumConstants from 
Class#getEnumConstants()/Class#getSharedEnumConstants().

Currently consider the following example:
```java
enum E {
    A, B, C
}
E[] values = E.values();
E[] constants = E.class.getEnumConstants();
assert Arrays.equals(values, constants);
```
These methods provide an equal array of values, but they are treated 
differently. This is because the _constants_ stored by Class#enumConstants are 
non final and declared volatile. So C2 can't trust this call. Consider if I 
only wanted to access the value from an offset from these arrays.
```java
E value = values[0];
E constant = constants[0];
assert value == constant;
```
_constant_ would never be folded but _value_ would be.

So I propose the addition of @Stable annotation added to Class#enumConstants so 
_constant_ can be folded by C2. This is not a trivial change as it requires 
changing the data race to abide by @Stable. Could I be sponsored for this 
change (JBS issue as well)?

A future proposal would be adding @Stable to Class#enumConstantDirectory, 
though that can be a seperate enhancement as that might require changing of the 
data structure to allow folding. Let me know if it should be combined as the 
Stable annotation itself would be implemented in a similar way for both.

Thanks,
Ryan Hallock

Reply via email to