Video in progress

The company's shared library has to work on Java 17, 21 and 25 services at the same time. How do you use --release, multi-release JARs and toolchains?

I compile the library with --release 17 for the lowest supported version, put the places that need a new API into the META-INF/versions/21 part of a multi-release JAR, and test on all target JDKs in CI. Toolchains make the build independent of the local JDK.

📖 Answer

--release, not -source/-target. -target 17 only sets the class file version, but it compiles against the JDK 21 library, so you can unknowingly use List.getFirst() (Java 21) and get a NoSuchMethodError on Java 17. --release 17 checks against the Java 17 API.

java {
    toolchain { languageVersion = JavaLanguageVersion.of(21) }
}
tasks.withType<JavaCompile>().configureEach { options.release = 17 }

A multi-release JAR. When there is a better way on a newer version (for example virtual threads or FFM):

mylib.jar
├── com/acme/io/BufferPool.class                 # Java 17 implementation
└── META-INF/versions/22/com/acme/io/BufferPool.class   # with FFM

Multi-Release: true goes in the manifest. The JVM takes the class matching its own version. The rule: the public API should be identical in both, and only the implementation differs. The build and testing are more complex, so do it only where you really need it.

A runtime check is sometimes simpler than an MR-JAR:

if (Runtime.version().feature() >= 21) { /* ... */ }

But this code can't call the new API without reflection.

A CI matrix. Tests run on 17, 21 and 25. Testing only on the highest one is the most common mistake.

Dependencies. The library's transitive dependencies must support 17 too, otherwise a conflict appears in the consumer service. Keep dependencies few where possible, and don't shade (shading hides CVEs).

Policy. When to raise the minimum version: for example, 6 months after 90% of the fleet has moved to the new LTS. Announcing it in advance and doing it with a major version prevents unexpected breakage for consumers.