On Tue, 24 Jun 2025 00:04:54 GMT, Chen Liang <li...@openjdk.org> wrote:

> Unsafe throws IAE for misusing static vs instance fields, and it's revealed 
> that AtomicXxxFieldUpdaters are using this mechanism to reject static fields. 
> This is not a good practice, but we can at least document this so we don't 
> accidentally introduce problems.

I noticed that the native implementation of 
`Unsafe​::array⁠(BaseOffset​/IndexScale)` refers to the non‑existent class 
`java.lang.InvalidClassException` instead of 
`java.lang.IllegalArgumentException` (which results in 
`java.lang.NoClassDefFoundError` being thrown):
https://github.com/openjdk/jdk/blob/1ca008fd02496dc33e2707c102560cae1690fba5/src/hotspot/share/prims/unsafe.cpp#L587-L594

src/hotspot/share/prims/unsafe.cpp line 498:

> 496:       if (fs.access_flags().is_static()) {
> 497:         offset = -1;
> 498:       } else {

Since `offset` is initialised to `-1`, this can simply do:
Suggestion:

      if (!fs.access_flags().is_static()) {

src/java.base/share/classes/jdk/internal/misc/Unsafe.java line 1070:

> 1068:      *
> 1069:      * @throws NullPointerException if the field is {@code null}
> 1070:      * @throws IllegalArgumentException if the field is static

Maybe these checks could be done in **Java** like:

// implicit null check:
if ((f.getModifiers() & ACC_STATIC) != 0) {
        throw new IllegalArgumentException("Field is static");
}

and for the `staticField(Offset/Base)` methods:

// implicit null check:
if ((f.getModifiers() & ACC_STATIC) == 0) {
        throw new IllegalArgumentException("Field is not static");
}

src/java.base/share/classes/jdk/internal/misc/Unsafe.java line 1092:

> 1090:      *         in class {@code c}, i.e., if {@code 
> c.getDeclaredField(name)}
> 1091:      *         would throw {@code java.lang.NoSuchFieldException}, or 
> if such
> 1092:      *         a field is static

This is actually not the case, the native code only checks whether the field 
exists, not whether it’s also not `static`:
https://github.com/openjdk/jdk/blob/cbcf401170e0600e48ef74770eaa47c84c7e50b0/src/hotspot/share/prims/unsafe.cpp#L492-L503

Suggestion:

     *         would throw {@code java.lang.NoSuchFieldException}.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/25945#issuecomment-3007131955
PR Review Comment: https://git.openjdk.org/jdk/pull/25945#discussion_r2164661450
PR Review Comment: https://git.openjdk.org/jdk/pull/25945#discussion_r2164571411
PR Review Comment: https://git.openjdk.org/jdk/pull/25945#discussion_r2164571852

Reply via email to