Skip to content

A @NullMarked alternative without @Target(MODULE) #795

Open

Description

@cpovirk

We still see people avoid JSpecify (or at least @NullMarked) on occasion because of various issues that come up in a small fraction of cases but that do come up at scale. Those issues come up with Java 8 and with Android.

As a result, people avoid @NullMarked (and perhaps JSpecify entirely) in some cases:

Or they do what we've done in some Google projects, which is to use @NullMarked at the package level (where it's safer), applying @NullUnmarked (which is always safe) to individual classes as an override where necessary. But I otherwise slightly recommend against package-level annotations, so this makes me sad.

"Luckily," there are of course many alternative artifacts of nullness annotations, and we of course created JSpecify because none of them quite met the common requirements that we identified. But we consciously made a tradeoff between Java 8 and Java 9+, with the knowledge that someday Java 8 would be safe to ignore. (We may have given less attention than we should have to the similar Android issue, even though the issue there is entirely(?) with runtime reflection, which is generally a bad idea on Android, anyway.)

(Regarding other artifacts of annotations, I'll note here that the JetBrains annotations in particular became more appealing with the introduction of their @NotNullByDefault annotation, and it's possible that they'll someday be recognized by Kotlin. If so, the main downside I'm aware of that would remain is that they are "hybrid" annotations, which makes it impossible to write @Nullable T[] without annotating both the array elements and the declaration (i.e., the array) itself. (This is more fodder for #123.))

One of the Java 8 issues will finally go away when people build with Java 27, which we recommend doing once it's released, even when targeting older versions. But others will remain, as will the Android issue.

So perhaps we should introduce @NullMarkedCompat or @NullMarked.WithoutTargetModule or something similar. We'd have to get tools to recognize it as equivalent to @NullMarked. Then people could use that even in the situations in which @NullMarked can lead to trouble today.

I'm still not sure what to think, but I wanted to get this all down in one place, since I keep posting pieces of it all over the place.

Activity

  1. tbroyer commented on Apr 14, 2026

    @tbroyer

    Fwiw, for gradle-kotlin-accessors-generator, it's an annotation processor so the annotation is actually purely compile-time, as no one will build against the processor (which doesn't even expose any public API beyond javax.annotation.processing.Processor).

    This sets it appart, IMO, from a library that people will depend on, and for which I'd really want a JDK8-compatible flavor of JSpecify (for as long as JDK8 is supported)

    I also thought about requiring JDK 11+ for the annotation processor (as I think one should use a recent JDK even if targeting older versions, --release works great as long as you don't need to open modules, so for 99.9% of cases), but using JetBrains annotations was cheap.
    Nowadays, I write my libraries with JDK 21 as the baseline, I could have even gone with that same baseline for the annotation processor (many other build-time tools require more recent JDKs), and might very well change my mind.

    Anyway, all this to say that gradle-kotlin-accessors-generator is probably not a compelling example here 😉

  2. cpovirk commented on Apr 16, 2026

    @cpovirk
    CollaboratorAuthor

    William Leung notes that we could also publish a second version of the JSpecify jar without MODULE on NullMarked. I'm a little nervous about this: Users might not get the version that they want, thanks to various complexities of builds, either at build time or at runtime. But it does have the virtue of requiring zero effort from tool providers.

    (reminder that we tried multi-release jars and found that they weren't meant to solve this problem)

  3. lwr commented on Apr 17, 2026

    @lwr

    I still believe that publishing a separate org.jspecify:jspecify-java8 was the best decision.

    It will keep things simple and consistent from now on, as you previously noted in JetBrains/java-annotations#113 (comment)

    given that a separate annotation would feel a bit awkward today and more awkward over time. So I'll just agree that adding MODULE does carry downsides.

    Implementation Strategy

    • For Library Maintainers:
      The recommendation would be to declare a dependency on the standard org.jspecify:jspecify (ideally with <optional>true</optional>). During development, they can use org.jspecify:jspecify-java8 in the parant POM, then swap it back to the standard artifact during the publishing phase to maintain metadata integrity.
    • For End Users/Application Developers:
      Those requiring strict Java 8 compatibility can simply exclude the standard JSpecify transitively and include jspecify-java8 as a direct dependency for their own codebase.

    Exploring Further: For "Compact" Version

    Furthermore, I suggest naming this artifact org.jspecify:jspecify-compact rather than specifically "java8." This version would:

    • Remove META-INF/9, and @Target(ElementType.MODULE) from @NullMarked.
    • Change all @Retention(RetentionPolicy.RUNTIME) to CLASS.

    Many users only require JSpecify for static analysis and code linting. They do not need the overhead of runtime-visible annotations.

    I strongly believe that serialization frameworks and other heavy-duty tooling should remain decoupled from a general-purpose nullity metadata library. JSpecify should excel as a linting standard without imposing its metadata on runtime reflection by default.

  4. cpovirk commented on Apr 17, 2026

    @cpovirk
    CollaboratorAuthor

    Thanks, that's great information to think about. I could see pulling something like we at Google did with Guava, in which you can use the artifact version to pick between different "flavors." But for JSpecify, I think that a second artifact ID would at least be more workable, even if I'm not sure what would be best at this point. (And probably Gradle Module Metadata could help users here, maybe even in picking the right version automatically, though I've felt useless when users have been unsure how to work with that feature in Guava.)

    Your last point does remind me that users could want any combination of {MODULE support, no MODULE support} and {RUNTIME, CLASS}. Maybe that's more reason to go with some artifact-based solution rather than adding one three more annotations.

    Incidentally, I'm curious what kind of runtime overhead you're referring to. The big potential problem is people who reflect on NullMarked itself—that is, people who don't merely look up NullMarked and other annotation that appear on an element but rather operate on what we could call NullMarked.class—in older Android and Java 8 environments where MODULE isn't present. But when I think about plain "overhead," I'd say that CLASS and RUNTIME are equivalent, since both end up in the class file. (And on the Android front, type-use annotations don't show up in the dex/apk, so the only ones that matter there are NullMarked and NullUnmarked.)

    (I thought that we had some issue open about providing standard CLASS-retention equivalents. But I don't see an issue specifically about that, even as I see #28, #96, #234, #389, and likely others. I am probably confusing it with #410, which is not amenable to the artifact-based approach.)

  5. lwr commented on Apr 18, 2026

    @lwr

    Reflecting on the design, if we were pre-1.0, a mirrored runtime package might have been a cleaner way to handle this decoupling. Similarly, had the Java ecosystem adopted a less intrusive metadata approach for modules (akin to Kotlin’s file annotations), we wouldn't be facing this binary compatibility wall.

    Since we cannot change those foundational decisions, providing a specialized -java8 or -compact artifact is the most effective way to 'emulate' that missing layer of decoupling. It allows us to achieve the goal of a 'linting-only' footprint without breaking the 1.0 API contract.

  6. lwr commented on Apr 18, 2026

    @lwr

    Anyway, exploring this further, have we considered introducing a nested/inner-scope strategy for @NullMarked as a more flexible alternative to MODULE level annotations?

    Instead of relying on the coarse-grained MODULE target (which triggers the binary compatibility issues we've discussed), providing a more granular, nested-capable @NullMarked could offer superior flexibility:

    Composition over Hierarchy: A "nested-friendly" @NullMarked allows developers to opt-in to null-safety at the exact boundary they need—be it a top-level class or a specific nested utility—without needing to annotate the entire module.

    Bypassing the Compatibility Wall: By focusing on TYPE, METHOD, or even CONSTRUCTOR targets for nested scopes, we achieve the same goal of "broad coverage" through composition rather than through a top-down MODULE constant that older compilers don't recognize.

    The "Kotlin-esque" Granularity: This aligns better with how modern languages handle metadata—providing tools to define scope where it makes sense, rather than forcing a dependency on the latest JVM metadata structures.

    The Nested Strategy provides the "logical" flexibility that MODULE targets were originally intended to solve, but in a way that remains safe for the legacy ecosystem.

    I've always felt that the more we can decouple the intent of null-marking from the infrastructure of the Java Module System, the more resilient JSpecify will be across the diverse range of environments it aims to support.

  7. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    I'm not sure if I'm following the discussion of file-level annotations and composition. Are you making further arguments for removing MODULE or proposing something further?

  8. lwr commented on Apr 18, 2026

    @lwr

    for compatibllity issue we cannot do it after 1.0, but we can provide a ScopedNullMarked adding a nested property to resolve it, as an alternate choice for -java8 arifact

  9. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    How would ScopedNullMarked be different from the current NullMarked, aside from not supporting MODULE?

  10. lwr commented on Apr 18, 2026

    @lwr

    yes

    • no module level anymore
    • add nested property for flexibility
  11. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    Thanks. Can you explain what you mean by a nested property? Is this something like @ScopedNullMarked(nested = false), for example?

  12. lwr commented on Apr 18, 2026

    @lwr

    I think it would be identity to NulllMarked by default, @ScopedNullMarked(nested = true) is optional usage to simulate model level.

    Default to nested or one-level are both acceptable by your decision

  13. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    Ok, it sounds like this may be a proposal for an annotation that could make a class declaration null-marked (affecting its type-parameter declarations) but not its methods or fields? Similarly, it could be used to make a method null-marked but not any classes nested inside it or any of the type arguments or array-component types of its local variables? Is that what you have in mind?

  14. lwr commented on Apr 18, 2026

    @lwr

    Sorry for confusing, the nested suggestion should be corrected to withSubpackages, and the name can be @ScopedNonNull(withSubpackages = true)

  15. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    Ah, got it, thanks. Inclusion of subpackages is one thing that we are unlikely to choose to support: We understand the convenience, but "subpackage" isn't a well-defined concept in Java, and furthermore, it would mean that people looking for @NullMarked would need to look not only in a class and its package and its module but also in any parent packages. If you have something else to add to that discussion, you could post it on #8, but again, I would not expect a change there.

    As for the MODULE target and CLASS vs. RUNTIME: I don't expect us to do anything here soon, but it's clearly worth keeping on the table:

    • If you (or anyone else) knows of specific downsides to RUNTIME relative to CLASS, I'd be interested in hearing them. Gemini suggests that there is some impact on class loading (or, to a greater extent, on reflection that reads the annotations) and memory retention (but more so with larger values like strings). I haven't heard anyone talk about that in the past, so it might be negligible in practice. (Or it might be a blind spot :))
    • That reminds me that CLASS and RUNTIME annotations are written into different sections of the class file. This could have various effects:
      • If a library builds with the CLASS version and someone runs with the RUNTIME version, are the annotations visible at runtime or not? And which behavior is desired? Does this produce warnings? (Or maybe there are warnings for a similar scenario at build time?)
      • Would the JVM end up paying some of the cost referred to above for anything in the runtime-visible section, even if it later discovers that that annotation actually has only CLASS retention at runtime?

    That does make me less enthusiastic about providing different versions. (I might feel differently if we there were a magic way to ensure that the CLASS version were used only at runtime.)

  16. cpovirk commented on Apr 18, 2026

    @cpovirk
    CollaboratorAuthor

    That does make me less enthusiastic about providing different versions.

    I was worrying there specifically about providing different versions of the artifact, with the same annotations in each but with different retention.

    But I'm realizing that I might likewise find worries for an approach that offers both NullMarked and NullMarkedClassRetention: What if users mix NullMarked with NullableClassRetention? For that matter, who would stand for the name "NullableClassRetention?" :) (And "NullableClass" sounds like it could be another name for NullUnmarked!)

    So, I'd probably be nervous about different retentions at all.

    But those concerns are less likely to apply to a difference in target. Still, it would be good to check what happens if an annotation appears on a module in a class file but lacks MODULE target at runtime or compile time. Similar to above, it would be nice if users could opt in to dropping the MODULE target only at the "top level" of the dependency tree so that no library can use it to cause trouble for downstream users.

  17. lwr commented on Apr 19, 2026

    @lwr

    I have not digest the behavior what jvm does while loading classes with annotations that not matched with the annotation class definition. I thnk it should not be visible for runtime, as that you cannot see the annotation in classfile if it is defined as SOURCE retention while compiling and later changed to CLASS.

    Dont concern about the naming. If it is pre-1.0 now, I would suggest that all retentions changed to CLASS, copy all 4 annotation classes to subpackage org.jspecify.run time and get the same names

  18. vlsi commented on Aug 23, 2026

    @vlsi

    (reminder that we tried multi-release jars and found that they weren't meant to solve this problem)

    That conclusion looks worth re-testing. On current compilers the compile-time failure behind #245 does not reproduce, and the kotlinc gap recorded there turns out to be harmless for this particular difference.

    How I tested. I built a probe jar whose root entry and META-INF/versions/9 entry hold the same annotation differing only in @Target, with Multi-Release: true in the manifest. Annotating a declaration that only one of the two @Target sets allows then shows which entry a compiler read.

    Compiler Mode Entry read
    javac 21.0.9 --release 8 root
    javac 21.0.9 --release 11 META-INF/versions/9
    kotlinc 2.3.0 default root

    What that gives a NullMarked whose root entry omits MODULE. Run directly against such a jar:

    Why #245 saw otherwise. That thread traced the Caffeine failure to Gradle not passing --release, rather than to javac (comment). Gradle passes it today: options.release.set(8) in the pgjdbc build is how I hit the warning to begin with.

    What I have not tested: Maven, Bazel, Turbine, the Android toolchain, IDEs, and anything that reflects on NullMarked.class itself rather than on the annotations of an element. #245 also concluded that the versions should not differ in their API, and @Target is exactly such a difference, so that decision would have to be reopened deliberately rather than in passing.

    For context: pgjdbc targets Java 8, builds with javac 21 and -Werror, and the warning fires on every package-info.java that carries @NullMarked.

  19. cpovirk commented on Aug 23, 2026

    @cpovirk
    CollaboratorAuthor

    Thanks.

    I'd have to go back and reread a bunch on this, but your report does match my memory (and the first comment of #245, which links to #34 (comment)) that this has always worked with plain javac. javac may have been our original testing approach, and then things went south from there :)

    The Gradle question is still confusing to me:

    It would be interesting to see how Gradle would handle things today if we had a jar with a second Java 9+ version of NullMarked. My suspicion is that it would avoid the warning that you were seeing but then prevent use on modules again, but I don't know. Behavior may well even vary across versions, but it would be hard to do something that breaks some Gradle version.

    Thanks also for the suggestion of -Xlint:none,deprecation, etc.

  20. vlsi commented on Aug 24, 2026

    @vlsi

    It would be interesting to see how Gradle would handle things today if we had a jar with a second Java 9+ version of NullMarked. My suspicion is that it would avoid the warning that you were seeing but then prevent use on modules again

    I built that jar and measured it: https://github.com/vlsi/jspecify-mrjar-playground

    The suspicion does not reproduce. The multi-release jar is quiet on Java 8 and every module-info.java carrying @NullMarked still compiles and runs, in all 48 cells that run — javac 8, 11, 17, 21 and 25, Gradle 7.4.2, 8.14.4 and 9.5.1, Maven 3.9, kotlinc 2.3.

    variant ok warn fail
    1.0.1 (published) 32 16 0
    replica of 1.0.1 32 16 0
    MODULE dropped 32 0 16
    multi-release 48 0 0
    multi-release, module-info.class in versions/9 too 48 0 0

    The MODULE-dropped column is the control: those 16 failures are annotation interface not applicable to this kind of declaration on module-info.java, in every tool. Without them, "no warnings" would prove nothing. The replica matches the published jar cell for cell, and its four class files are byte-identical to the ones in jspecify-1.0.1.jar.

    Two things that narrow the problem more than I expected:

    • Only --release 8 sees the warning. -source 8 -target 8 compiles against the running JDK's own ElementType, so it never warns, whatever jar it reads. Calcite sets sourceCompatibility/targetCompatibility and hits nothing; pgjdbc sets options.release and hits it on every package-info.
    • Only the project that writes @NullMarked sees it. A project that merely depends on a null-marked library never does, so the blast radius is annotating projects, not their users.

    Which entry each compiler reads follows the flag, and the build tools add nothing of their own — every Gradle and Maven row matches the javac row with the same flags:

    compiler and flags entry read
    javac 8, no flags root
    --release 8 (javac 11 … 25) root
    -source 8 -target 8 root
    --release 9 and above META-INF/versions/9
    kotlinc 2.3 root

    gradle#19587

    It is still real, and it is worth being precise about what triggers it, because the answer decides whether a multi-release jspecify jar is safe. gradlew run on a modular application:

    Gradle com.formdev:flatlaf:2.0 (the dependency from the issue) jspecify, module-info.class only in versions/9 the same jspecify jar, manifest written last
    9.5.1 ok ok ok
    8.14.4 fail ok fail
    7.4.2 fail ok fail

    The failure is error: module not found: com.formdev.flatlaf, and Gradle passes the jar as -classpath instead of --module-path.

    The two jspecify columns hold identical entries — same classes, same META-INF/versions/9/module-info.class, same Multi-Release: true. They differ only in where META-INF/MANIFEST.MF sits in the archive, and that is the whole bug. Gradle's JavaModuleDetector asks JarInputStream for the manifest, and JarInputStream reports a manifest only when it appears among the first entries. FlatLaf 2.0 writes its manifest after the classes, so Gradle never learns the jar is multi-release, never looks at META-INF/versions, and concludes the jar is not a module. Gradle 9.5.1 gets all three right.

    So the practical rule for a multi-release jspecify jar: anything that writes the manifest first — the jar tool, Gradle's Jar task, Maven — stays clear of this even on Gradle 7. A repackaging step that reorders entries would not.

    What I did not test

    Bazel, Turbine, the Android toolchain, ecj, IDE compilers, and tools that reflect on NullMarked.class itself (Error Prone, NullAway) rather than on an element's annotations.

    And the objection from #245 stands untouched: a multi-release jar whose releases differ in @Target is an API difference between releases, which that issue ruled out on principle. Worth noting that the JDK's own tooling does not treat it as one — jar --release 9 rejects a versioned class whose methods differ from the root, but accepts these two NullMarked copies. That is a data point, not an argument; the decision is still yours to reopen deliberately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions