Video in progress
If your library has to support Java 11 and Java 21 users at the same time, how do you set that up?
The main code is built with --release 11; for the places that need newer APIs, use a multi-release JAR (META-INF/versions/21/) or an optional implementation detected at runtime. Testing on every supported JDK in CI is mandatory.
📖 Answer
The first step is the --release flag, not -source/-target. --release 11 also restricts the compiler to the Java 11 API; -target 11 lets you use the newer JDK API, and the code then fails on Java 11 with NoSuchMethodError. This is the most common mistake.
Ways to use a new feature:
- A multi-release JAR (Java 9+).
mylib.jar
├─ uz/lib/ThreadSupport.class // the Java 11 version
└─ META-INF/versions/21/
uz/lib/ThreadSupport.class // the version with virtual threads
Multi-Release: true in MANIFEST.MF. The JVM picks the class that matches its own version. In Maven, a second compile execution with --release 21 and a separate source folder.
The limitations: the public API has to be the same in both versions; the IDE and some build tools (shading, old plugins) process an MRJAR incorrectly; when debugging, always check which version was loaded.
- Runtime detection.
static final boolean VIRTUAL = Runtime.version().feature() >= 21;
Call the new API through reflection or MethodHandle. It's simpler, but you have no compiler help.
- Separate artifacts (
mylib-jdk21): the clearest, but it puts the burden of choosing on the user.
With language features (records, sealed, pattern matching) the problem is different: at the bytecode level they don't work on an old JVM, so in the public API you use them only if the lowest supported version allows it.
The organizational side:
- announce the support policy: "the last two LTS", and say in advance when you'll drop one;
- a CI matrix: 11, 17, 21 (and the latest non-LTS, to see future breakages early);
Automatic-Module-Nameormodule-info: in an MRJAR,module-infocan be versioned too.
Supporting each old version has a cost. Deciding when to drop one based on statistics (Maven Central downloads, internal telemetry) is a staff-level decision.
Sign up to mark studied questions and save your progress.