Workbench / Volume 3 Companion: The Backend
V3·42
Modules and Packaging
Companion to Volume 3, chapter 42: how artifacts, the class path and module path, executable JARs and dependency conflicts connect; new angles (the class path as a queue where the first in line is served, a module as a shop with a counter and a back room, a runtime image as a packed suitcase); what the chapter simplifies, measured on JDK 21 and 25 and the build's stage 43: the same source giving different jar bytes on a different JDK because javac names lambdas differently, a jlink runtime that quietly lost its class-data-sharing archive, a module whose encapsulation vanished on the class path, and a change to a record that old class files ran with but the source wouldn't compile against; the theory behind them (reproducible builds, linking, encapsulation, API evolution); how jlink regenerates a CDS archive, from the JDK source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 42 has five parts: artifacts (JAR, WAR and EAR files, the manifest), finding classes at run time (the class path, the module path and JPMS, jlink and jpackage), executable JARs (fat and uber JARs, shading and relocation), dependency conflicts (why they happen, how resolution works, binary versus source compatibility, diagnosing and fixing) and packaging across languages.
The links worth remembering:
- The class path is a search order. The first copy of a class wins, and nothing records which version anyone needed. Most packaging failures come from that.
- A module states what it needs and what it shows. That lets the JVM refuse missing dependencies at startup, hide internals, and lets
jlinkbuild a runtime of exactly what's needed. - An artifact is the output of its inputs, and the toolchain is one of them. The same source with another compiler, another JDK or another clock is another artifact (Gaps 1).
Explain it differently
1. The class path is a queue where the first in line is served. Ask for com.acme.Money and the JVM walks the JARs in order and takes the first one it finds. A second, newer copy further back is never asked.
2. A module is a shop with a counter and a back room. Exported packages are on the counter; the rest is in the back room, for staff only. But the back room only has a door if the building is a shop: put the same goods in a warehouse (the class path) and anyone can walk in (Gaps 3).
3. A runtime image is a packed suitcase. jlink packs only the modules you list. Packing light is the point, but you only find out you left the charger behind when you need it: JFR's module, or the shared class archive that made starting quick (Gaps 2).
4. Binary compatibility is about phone numbers; source compatibility is about the phone book. A compiled class calls a method by its exact name and descriptor. If that number still answers, old code works, even if the phone book (the source API) has been reorganised so that new code written against it reads differently (Gaps 4).
5. A reproducible build is a recipe that names its oven. "Bake at 180 °C" gives the same cake only in the same oven. A build that pins sources and timestamps but not the compiler gives the same bytes only with the same JDK (Gaps 1).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12, Temurin 25.0.1 and the build's stage 43 (exp/43), unless stated.
1. A reproducible build has to pin the compiler too. The chapter and exercises make JARs reproducible by fixing timestamps and entry order. TiffinBox's jars already do (jar --date). Built twice with JDK 21 and once with JDK 25, both with --release 21:
JDK 21, build 1: 4c65f5dea3005d3b
JDK 21, build 2: 4c65f5dea3005d3b
JDK 25, build 1: cb20625ede60b47e
manifests:
Created-By: 21.0.12.1 (Ubuntu)
Created-By: 25.0.1 (Eclipse Adoptium)
class files that differ between JDK 21 and JDK 25: 13 of 106
the first lambdas javac generated in Extensions (constant pool order):
JDK 21: lambda$rawBytes$8 lambda$forEachRaw$7 lambda$fromWire$6 lambda$static$5
JDK 25: lambda$rawBytes$0 lambda$forEachRaw$0 lambda$fromWire$0 lambda$static$5
--release 21 fixes the API the code compiles against and the class file version, not the bytes javac writes. The manifest records the JDK, and the 13 classes that differ all contain lambdas, which the two compilers name differently. The names aren't only bytes: they appear in stack traces and profiles (stage 42's Server.lambda$new$23), so a profile taken before a JDK upgrade and one after can show different frames for the same code. A serialised lambda (rare, but some frameworks use them) refers to its synthetic method by name, so it can't be read back by the other build. A reproducible build names its JDK, down to the vendor and update; stage 43's tools/reproduce.sh prints it with the result.
2. jlink leaves the class-data-sharing archive out unless you ask. The chapter's trimmed runtime is about size. The full JDK ships a CDS archive (pre-parsed core classes, lib/server/classes.jsa); a jlink image doesn't have one unless --generate-cds-archive is given. Time from launch to the first answer on /health, median of 11 runs:
full JDK 21 (286 MB) median 289 ms (range 232 to 460)
full JDK, CDS off median 340 ms (range 313 to 368)
jlink, no CDS (54 MB) median 303 ms (range 268 to 385)
jlink + CDS archive (79 MB) median 272 ms (range 230 to 326)
jlink + CDS + app archive median 246 ms (range 189 to 321)
jlink with jdk.jfr, JFR on median 713 ms (range 640 to 790)
For TiffinBox, a small server, CDS is worth 30 to 50 ms, and an application archive (-XX:+AutoCreateSharedArchive, which stores TiffinBox's own classes too) another 25. With hundreds of framework classes the same archives save seconds. The archives cost 25 MB of the image (two of them: with and without compressed pointers). The last line is worth knowing too: starting JFR at launch added about 440 ms.
3. A module's encapsulation exists only when it runs as a module. The chapter's table puts everything on the class path in the unnamed module. Here is what that means for a module that does declare its API. kit exports kit.api and not kit.internal; App calls both:
== java -cp kit.jar:app App
through the API: 350
straight to the internal package: 350
== java --module-path kit.jar --add-modules kit -cp app App
through the API: 350
Exception in thread "main" java.lang.IllegalAccessError: class App (in unnamed module @0x79fc0f2f) cannot access class kit.internal.Paise (in module kit) because module kit does not export kit.internal to unnamed module @0x79fc0f2f
at App.main(App.java:4)
== javac --module-path kit.jar --add-modules kit App.java
src/app/App.java:4: error: package kit.internal is not visible
Same JAR, same module-info.class. On the class path the descriptor is ignored and the back room is open; compiled that way, App reached into the internals without a warning. Encapsulation is decided by how the JVM is launched. A library can't rely on it while most of its users run on the class path, which is why many libraries still document "internal" packages by name.
4. A record's components are its API in three ways. Stage 42 changed IdempotencyKey from record IdempotencyKey(String hex) to record IdempotencyKey(long hi, long lo), keeping a String constructor and a hex() method. A program compiled against stage 41's core:
== compiled against stage 41's core, run with stage 41's
equal after a round trip through hex(): true
record pattern: hex = 1898309fe931cabf17cc4423e1a658f4
record components: [java.lang.String hex]
== same class file, run with stage 42's core
equal after a round trip through hex(): true
record pattern: hex = 1898309fe931cabf17cc4423e1a658f4
record components: [long hi, long lo]
== recompiled against stage 42's core
Client.java:10: error: incompatible types: long cannot be converted to String
Client.java:10: error: incorrect number of nested patterns
Binary compatible: every method the old class file calls (of, <init>(String), hex(), equals) still exists, and the compiled record pattern is just an instanceof and a call to hex(). Source incompatible: a record pattern must list the current components. And visible to reflection: anything that serialises records by their components (Jackson, many JSON and binary codecs) would now write {"hi":…,"lo":…} instead of {"hex":…}. For a record, the component list is part of the API, the source contract and possibly the wire format at once.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Fixed timestamps make a JAR reproducible." | Only with the same compiler; JDK 25 changed 13 of 106 classes. | Gaps 1 |
"--release 21 gives the same class files on any JDK." |
It fixes the API and class file version, not the bytes. | Gaps 1 |
| "A jlink image is the JDK, smaller." | It drops the CDS archive unless asked, and every module you didn't list. | Gaps 2 |
"module-info makes my internals private." |
Only for users who put you on the module path. | Gaps 3 |
| "Binary compatible means users can upgrade without changes." | Until they recompile, or reflect over your record. | Gaps 4 |
| "Changing a method's return type is safe if callers ignore it." | The descriptor changes, so old callers fail with NoSuchMethodError. |
Exercises P1 |
"jdeps lists every module the service needs." |
Not the ones only operations use, like jdk.jfr. |
Exercises P8 |
Theoretical gaps: the ideas behind the chapter
1. Reproducible builds are a function of all inputs. The Reproducible Builds project defines a build as reproducible when the same source, build environment and instructions give bit-for-bit identical artifacts. "Build environment" includes the toolchain's exact version. The payoff is verification: anyone can rebuild and compare hashes, so a tampered artifact stands out.
2. Linking: early, late and lazy. C links statically (into the executable) or dynamically (at load time); the JVM links lazily, resolving a symbolic reference the first time it runs (chapter 40). Binary compatibility in Java is defined by these symbolic references (JLS chapter 13): a change is binary compatible if every pre-existing reference still resolves to something with the same meaning.
3. Encapsulation is enforced by whoever loads the code. Parnas (1972) argued for modules that hide their design decisions behind interfaces. A language can only enforce that where it controls loading: JPMS on the module path, OSGi bundles in a container, Go's internal/ directories at compile time. Everywhere else, encapsulation is a convention.
4. Semantic versioning has three compatibilities, not one. SemVer's "breaking change" bundles binary, source and behavioural compatibility. Tools like japicmp and revapi check the first two separately. Gaps 4 is a change that's binary compatible and source incompatible, which is a major version change for libraries whose users recompile, and a minor one for plugins that are only run.
Applying it
Code walkthrough
Gaps 2 is about the step jlink takes at the end. From openjdk/jdk21u, src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/CDSPlugin.java.
The image builds its own archive
private void generateCDSArchive(ExecutableImage image, boolean noCoops) {
List<String> javaCmd = new ArrayList<String>();
Path javaPath = image.getHome().resolve("bin").resolve(javaExecutableName());
if (!Files.exists(javaPath)) {
throw new PluginException("Cannot find java executable at: " + javaPath.toString());
}
javaCmd.add(javaPath.toString());
javaCmd.add("-Xshare:dump");
String archiveMsg = "CDS";
if (noCoops) {
javaCmd.add("-XX:-UseCompressedOops");
archiveMsg += "-NOCOOPS";
}
The plugin doesn't copy the JDK's archive: it runs the new image's own java -Xshare:dump. An archive records classes as loaded by one particular runtime, so it has to be made by the runtime that will use it.
Which classes, and why it can't cross platforms
public List<String> process(ExecutableImage image) {
targetPlatform = image.getTargetPlatform();
runtimePlatform = Platform.runtime();
if (!targetPlatform.equals(runtimePlatform)) {
throw new PluginException("Cannot generate CDS archives: target image platform " +
targetPlatform.toString() + " is different from runtime platform " +
runtimePlatform.toString());
}
Path classListPath = image.getHome().resolve("lib").resolve("classlist");
if (Files.exists(classListPath)) {
generateCDSArchive(image,false);
// The targetPlatform is the same as the runtimePlatform.
// For a 64-bit platform, generate the non-compressed oop CDS archive
if (Architecture.is64bit()) {
generateCDSArchive(image,true);
}
Two consequences. Because it runs the image, you can't generate the archive when building a Linux image on a Mac (the plugin refuses); build the image in the target's container, or let the first run make the archive. And on 64-bit it makes two archives, one for each pointer encoding, which is where most of Gaps 2's 25 MB went.
Debugging drills
D1. A reproducible build that didn't reproduce
A team's verification job rebuilds each release from its tag and compares the JAR's hash with the published one. Last week's release fails the check, though nobody changed the build and timestamps are fixed. Diffing the JARs shows the manifest and a dozen class files.
D2. The slim image starts slower
A service moved from a full JDK base image to a jlink runtime, cutting the image from 400 MB to 90 MB. Startup went from 6 s to 7.5 s, and the readiness probe now sometimes fails.
D3. A library's internals in production code
A platform team ships a library as a module with an internal package not exported. They change a class in it, and three services break with NoSuchMethodError in the internal package.
D4. Old clients work, new builds don't
After a library release, services that just upgraded the JAR keep working, but any service that recompiles fails to build, and one service's JSON output changed shape although it didn't touch that code.
Career-oriented
Interview prep
Mid-level 1: ClassNotFoundException and NoClassDefFoundError
Question. "What's the difference between ClassNotFoundException and NoClassDefFoundError, and what would you check for each?"
How to get there. Who asked for the class, and when.
Mid-level 2: a fat JAR or a layered image
Question. "We ship a fat JAR inside a container image. Someone suggests a layered image instead. What's the difference, and when does it matter?"
How to get there. What changes between releases, and what each layer caches.
Senior 1: modularising a codebase
Question. "Should we add module-info to our application's modules? What would we get and what would it cost?"
How to get there. Who launches the code, and which benefits need the module path.
Senior 2: a library's compatibility policy
Question. "You own a library used by 40 services. Write its compatibility policy."
How to get there. Separate binary, source and behavioural compatibility, and say how each is checked.
Staff 1: verifiable artifacts
Question. "After a supply-chain incident elsewhere, leadership asks: can we prove that what runs in production was built from our source? Design it."
How to get there. Reproducibility, provenance, verification at deploy.
Staff 2: the JDK upgrade across a fleet
Question. "We run 200 JVM services on JDK 17 and want to be on 21 within six months. How do you plan it?"
How to get there. What can break, how to find it before production, and how to roll out.