The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·42

Modules, Packaging and Dependency Conflicts

How Java code is packaged and found at run time: JAR and WAR files, manifests, the class path versus the module path, JPMS in practice, fat and uber JARs, Spring Boot's nested JARs and layered images, shading and relocation, jlink and jpackage. Covers why dependency conflicts happen and how to resolve them. Compared with Go's static binaries and minimal version selection, Rust's crates and semver-compatible duplicates, C and C++ libraries and ABIs, Zig, .NET assemblies, Python wheels and Node's node_modules.

29 topics · ~24 min read · 31-question quiz
Updated Suggest a correction

Start here: from classes to something you can ship

Packaging in one paragraph

javac turns each .java file into a .class file. A real application is thousands of classes of your own plus hundreds of libraries (other people's classes). To ship, you bundle classes into JAR files (zip archives with a META-INF/MANIFEST.MF), and at run time the JVM must be told where to find every class it might load: the classpath (a list of JARs and directories) or the module path. Most production problems in this chapter come from that search going wrong. Build tools (chapter 43) automate it, but they produce exactly these files and flags, so it pays to have done it once by hand.

Build, package, run

A tiny café app uses a money-formatting library:

Java
package com.cafe;
import com.acme.money.Money;
public class Main { public static void main(String[] a) {
    System.out.println("money library " + Money.version() + ": " + Money.format(12345));
    System.out.println(Money.formatWithGst(12345)); } }
Text
$ javac -d lib2/out lib2/src/com/acme/money/Money.java && jar cf money-2.0.jar -C lib2/out .     # the library
$ javac -cp money-2.0.jar -d app/out app/src/com/cafe/Main.java                                # compile against it
$ printf 'Main-Class: com.cafe.Main\nClass-Path: money-2.0.jar\n' > manifest.txt
$ jar cfm cafe.jar manifest.txt -C app/out .                                                    # an executable JAR
$ java -jar cafe.jar
money library 2.0: ₹123.45
₹129.62 incl. GST

The manifest names the class with main and lists the JARs to put on the classpath. Notice that javac needed the library to compile and java needed it again to run: compile-time and run-time classpaths are separate, and nothing checks that they match.

When a class can't be found

Text
$ java -cp app/out com.cafe.Main                          # forgot the library
Exception in thread "main" java.lang.NoClassDefFoundError: com/acme/money/Money
	at com.cafe.Main.main(Main.java:4)

NoClassDefFoundError means "this class was there at compile time but isn't on the run-time path". (Its cousin ClassNotFoundException comes from code that loads classes by name, like JDBC drivers or plugins.) Because classes load lazily, this can happen hours after startup, the first time a rarely used code path runs.

When two versions are on the path

Libraries depend on other libraries, so a real application often ends up with two versions of the same library (say, one library wants money 1.0 and another wants 2.0). On the classpath, the JVM takes the first matching class it finds:

Interactive diagram: First on the path wins: two versions of one library. It needs JavaScript; the text around it says the same.
Text
$ java -cp money-2.0.jar:money-1.0.jar:app/out com.cafe.Main
money library 2.0: ₹123.45
₹129.62 incl. GST

$ java -cp money-1.0.jar:money-2.0.jar:app/out com.cafe.Main
money library 1.0: Rs 123
Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.String com.acme.money.Money.formatWithGst(long)'

Same files, different order, different program. Version 1.0 was picked, the first line printed the wrong format, and the second line called a method 1.0 doesn't have. NoSuchMethodError, NoClassDefFoundError and AbstractMethodError at run time almost always mean a dependency conflict: code compiled against one version is running with another. Build tools pick one version per library (Maven: the nearest in the dependency tree; Gradle: the highest), and the full-depth sections show how to see and control that choice.

Modules: declared dependencies

The Java Platform Module System (JDK 9) adds a module-info.java to each JAR, declaring what it needs and what it exposes:

Java
module com.acme.money { exports com.acme.money; }          // com.acme.money.internal is NOT exported
module com.cafe { requires com.acme.money; }
Text
$ java -p mods -m com.cafe/com.cafe.Main                   # -p is the module path
money library 2.0: ₹123.45

Main.java:2: error: package com.acme.money.internal is not visible        ← using a non-exported package
java.lang.LayerInstantiationException: Package com.acme.money in both module com.acme.money.legacy and module com.acme.money

Modules check at startup what the classpath only discovers at run time: a missing module is an error before main runs, two modules can't both contain the same package, and code can't use packages a library didn't export. The JDK itself is modular, which lets jlink build a trimmed runtime containing just the modules your app needs: here 52 MB instead of the full JDK's 286 MB, ideal for container images. Most applications and frameworks still run on the classpath, but libraries increasingly ship module descriptors.

How deep to go in packaging and dependencies

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Build and run a JAR; explain the classpath
L2 Package executable and fat JARs; read dependency trees; add module descriptors
L3 Explain class loader search, version resolution strategies, shading, layered JARs, jlink and native images, compared with Go, Rust, Node and Python packaging
L4 Diagnose NoClassDefFoundError, NoSuchMethodError, split packages and duplicate classes
L5 Set dependency policies: BOMs, version alignment, upgrade cadence, supply-chain checks
L6 Run dependency governance across many services and teams

Artifacts

JAR files

A JAR (Java ARchive) is a ZIP file containing .class files, resources (application.yml, templates, SQL files) and metadata in META-INF/:

Text
orders-service-1.4.2.jar
├── META-INF/
│   ├── MANIFEST.MF                         ← metadata: Main-Class, Class-Path, versions
│   ├── services/                           ← ServiceLoader provider registrations
│   │   └── java.sql.Driver                 ← e.g. lists org.postgresql.Driver
│   ├── maven/com.shop/orders/pom.xml       ← build metadata (Maven adds it)
│   └── versions/21/…                       ← multi-release JAR: classes for newer JDKs
├── module-info.class                       ← only if it's a named module
├── com/shop/orders/OrderService.class
└── application.yml
Terminal
$ jar --create --file app.jar --main-class com.shop.App -C target/classes .
$ jar --list --file app.jar
$ jar --describe-module --file app.jar     # module name, requires, exports (or "automatic")
$ unzip -p app.jar META-INF/MANIFEST.MF

The manifest (META-INF/MANIFEST.MF) is a text file of Key: Value headers:

Text
Manifest-Version: 1.0
Main-Class: com.shop.App                  ← what `java -jar` runs
Class-Path: lib/jackson-core-2.19.0.jar lib/slf4j-api-2.0.17.jar   ← relative paths, space-separated
Automatic-Module-Name: com.shop.orders    ← stable module name for non-modular JARs on the module path
Multi-Release: true                       ← enables META-INF/versions/N overrides
Implementation-Version: 1.4.2             ← readable via Package.getImplementationVersion()
Add-Opens: java.base/java.lang            ← for executable JARs only (JDK 9+)
Enable-Native-Access: ALL-UNNAMED         ← FFM/JNI restricted access (JDK 22+)

Multi-release JARs (JDK 9) let a library ship one JAR with a baseline implementation plus optimised versions in META-INF/versions/21/ that are used only on JDK 21+.

ServiceLoader (META-INF/services/<interface> files, or provides … with in module-info) is Java's built-in plugin mechanism. JDBC drivers, java.time zone providers, SLF4J bindings and Jackson modules are discovered this way. Merging JARs carelessly can drop these files (below).

WAR and EAR files

A WAR (Web ARchive) packages a web application for deployment into a servlet container (Tomcat, Jetty, WildFly, WebSphere):

Text
shop.war
├── index.html, static/…              ← public web resources
├── META-INF/MANIFEST.MF
└── WEB-INF/                          ← not directly servable
    ├── web.xml                       ← deployment descriptor (optional with Servlet 3.0+ annotations)
    ├── classes/                      ← the app's own classes and resources
    └── lib/                          ← dependency JARs

The container provides the Servlet API, JNDI, connection pools and sometimes JPA. The WAR's dependencies are loaded by a per-application class loader, usually child-first. EAR files bundle several WARs and EJB JARs for Jakarta EE application servers.

The modern shift: instead of deploying many WARs into one shared, long-running app server, each service ships as a self-contained executable JAR with an embedded server (Spring Boot, Quarkus, Micronaut, Helidon), packaged into a container image. One process, one app, isolated dependencies, and the container is the unit of deployment. Spring Boot still supports building a WAR (SpringBootServletInitializer) for organisations with existing app servers.

Finding classes at run time

The class path

The class path is an ordered list of directories and JARs that the application class loader searches for classes and resources:

Terminal
$ java -cp target/classes:lib/jackson-databind-2.19.0.jar:lib/jackson-core-2.19.0.jar com.shop.App
# ':' separator on Linux/macOS, ';' on Windows. Wildcard lib/* includes all JARs in a directory (unordered!).

Its semantics are simple, and so are its failure modes:

  • First match wins. If two JARs contain com/fasterxml/jackson/core/JsonParser.class, whichever comes first is used. There's no error and no warning.
  • No dependency information. The class path doesn't know which JAR needs which, or which versions are compatible.
  • Split packages are allowed: classes of one package can come from several JARs.
  • Everything is visible to everything. public means public to the world, and internal packages of libraries are fair game.
  • Failures are lazy: a missing class surfaces only when code first touches it, possibly hours after startup, as NoClassDefFoundError.

That's "JAR hell", and it's why build tools (chapter 43) manage dependency resolution and why JPMS exists.

The module path and JPMS in practice

The module path (--module-path / -p) holds modules. Each JAR with a module-info.class is a named module that declares its dependencies and exports (chapter 39). At startup the JVM resolves the module graph, failing fast on:

  • a missing required module ("Module not found"),
  • split packages (two modules containing the same package),
  • cycles in requires,
  • two modules with the same name.
Terminal
$ java --module-path mods:libs --module com.shop.orders/com.shop.orders.App
$ java --list-modules
$ jdeps --module-path libs --print-module-deps app.jar       # which JDK modules does the app need?
$ java --show-module-resolution -p mods -m com.shop.orders    # trace resolution

Three kinds of modules coexist:

Kind How Reads Exports
Named (explicit) JAR with module-info.class on the module path Only what it requires Only packages it exports
Automatic Plain JAR placed on the module path Every other module (including the unnamed one) All its packages. Name from Automatic-Module-Name, or derived from the file name (fragile: jackson-databind-2.19.0.jar → jackson.databind)
Unnamed Everything on the class path Everything Everything (to other unnamed code); named modules can't require it

Migration paths: top-down (modularise the application while libraries remain automatic modules) or bottom-up (libraries first). In practice:

  • Applications (Spring Boot, Quarkus) mostly stay on the class path. Frameworks need deep reflection everywhere, which would require opens declarations for each package or --add-opens.
  • Libraries should at least add an Automatic-Module-Name to their manifest so they have a stable module name.
  • JDK internals are encapsulated regardless: class-path code also can't reflectively access java.base internals without --add-opens (since JDK 16/17).

jlink builds a custom runtime image containing only the JDK modules your application needs. That gives smaller container images and a smaller attack surface:

Terminal
$ jdeps --ignore-missing-deps --print-module-deps --multi-release 25 --class-path 'lib/*' app.jar
java.base,java.logging,java.naming,java.net.http,java.sql,jdk.crypto.ec,jdk.management
$ jlink --add-modules java.base,java.logging,java.naming,java.net.http,java.sql,jdk.crypto.ec,jdk.management \
        --strip-debug --no-header-files --no-man-pages --compress zip-6 --output /opt/jre
# A full JDK is ~300 MB; such a runtime is often 50–80 MB.

This works for class-path applications too: jlink only needs to know the JDK modules. jpackage builds platform installers (.msi, .pkg, .deb, .rpm) with a bundled runtime, for desktop and CLI distribution.

Executable JARs

Fat and uber JARs

To run with java -jar app.jar and nothing else, you need all dependencies inside. There are three approaches:

Approach How Pros Cons
Uber JAR (unpacked/merged): Maven Shade, Gradle Shadow Extract every dependency's classes into one JAR Works with any launcher, one flat class path Collisions: identical paths overwrite each other (META-INF/services/*, META-INF/spring.factories, module-info.class, LICENSE, reference.conf). Needs transformers to merge. Signatures on signed JARs break
Nested JARs (JAR of JARs): Spring Boot Dependencies stay intact as JARs in BOOT-INF/lib/, loaded by a custom launcher No merging problems; each library keeps its identity and metadata Needs Spring Boot's JarLauncher and class loader; slightly slower class loading
Thin JAR + lib folder Class-Path: manifest entries pointing to lib/*.jar next to the JAR Simple; maps nicely onto container layers Multiple files to ship

Spring Boot's executable JAR layout:

Text
app.jar
├── META-INF/MANIFEST.MF
│     Main-Class: org.springframework.boot.loader.launch.JarLauncher     ← Boot's launcher
│     Start-Class: com.shop.App                                          ← your main class
├── org/springframework/boot/loader/…                                    ← launcher classes (unpacked)
└── BOOT-INF/
    ├── classes/        ← your code and resources
    ├── lib/            ← dependency JARs, unmodified
    ├── classpath.idx   ← class path order
    └── layers.idx      ← layer assignment for container images

Layered JARs for container images: dependencies change rarely, and your code changes on every commit. Boot can extract the JAR into layers so Docker caches the big dependency layers:

Dockerfile
FROM eclipse-temurin:25-jre AS extract
WORKDIR /app
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=extract /app/extracted/dependencies/ ./           # rarely changes → cached
COPY --from=extract /app/extracted/spring-boot-loader/ ./
COPY --from=extract /app/extracted/snapshot-dependencies/ ./
COPY --from=extract /app/extracted/application/ ./            # changes every build: a small layer
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "org.springframework.boot.loader.launch.JarLauncher"]

Or use Cloud Native Buildpacks (./mvnw spring-boot:build-image, ./gradlew bootBuildImage), which do this automatically with a tuned JRE, or Jib (builds layered images straight from Maven or Gradle with no Dockerfile or Docker daemon). Chapter 47 covers container images, CDS and AOT for Spring Boot.

Shading and relocation

Shading means bundling a dependency inside your JAR, usually with relocation: rewriting its package names (and every bytecode reference to them) into your own namespace:

XML
<!-- maven-shade-plugin: relocate Guava so our copy can't clash with the application's Guava version -->
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <executions><execution><phase>package</phase><goals><goal>shade</goal></goals>
    <configuration>
      <relocations>
        <relocation>
          <pattern>com.google.common</pattern>
          <shadedPattern>com.acme.sdk.shaded.com.google.common</shadedPattern>
        </relocation>
      </relocations>
      <transformers>
        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>  <!-- merge META-INF/services -->
        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
          <mainClass>com.acme.Tool</mainClass>
        </transformer>
      </transformers>
      <filters><filter><artifact>*:*</artifact><excludes><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.RSA</exclude></excludes></filter></filters>
    </configuration>
  </execution></executions>
</plugin>

When it's appropriate: libraries and SDKs with a dependency that commonly conflicts (Guava, Netty, Jackson, Protobuf) that you can't afford to leak to users. Elasticsearch clients, Hadoop, and various cloud SDKs ship shaded variants. Costs: bigger artifacts, duplicated code in memory, no security patches from the user's dependency upgrades (you must re-release), reflection or configuration that references class names by string can break, and confusing stack traces.

Applications rarely need relocation. Resolve conflicts at the build level instead.

Dependency conflicts

Why conflicts happen

Your service depends on library A (needs jackson-databind 2.15) and library B (needs jackson-databind 2.19). The JVM's flat class path can hold only one version of com.fasterxml.jackson.databind.ObjectMapper. Something has to choose. These diamond dependencies are inevitable in large dependency graphs:

your service lib-a 3.1 lib-b 5.0 jackson-databind 2.15 jackson-databind 2.19 vs one class path → one version wins (Maven: nearest; Gradle: highest) → NoSuchMethodError if the winner changed an API the loser used
A diamond dependency. Two libraries need different versions of the same artifact; the class path can load only one, so the build tool picks one, and binary incompatibility shows up at run time.

How resolution works

Tool / ecosystem Strategy when versions conflict
Maven Nearest wins: the version declared closest to your project in the tree. If depths are equal, first declaration wins. It can pick an older version silently. <dependencyManagement> and BOMs pin versions explicitly
Gradle Highest version wins (optimistic upgrade) by default, with rich version constraints (strictly, require, prefer, reject), platforms/BOMs, and failOnVersionConflict()
Go modules Minimal Version Selection (MVS): the build uses the minimum version that satisfies every requirement, i.e. the highest of the minimums stated. Deterministic with no lock-file solver, upgrades happen only when someone asks. Major versions ≥ 2 have different import paths (/v2), so v1 and v2 coexist
Rust (Cargo) SemVer-compatible requirements are unified to one version; incompatible major versions coexist in the same binary (serde 1.x and a hypothetical serde 2.x both compiled in, as distinct crates). Cargo.lock pins exact versions
npm / Node Nested node_modules: multiple versions coexist where needed (deduplicated when compatible). No conflict, at the cost of duplicates and subtle "two copies of React" bugs
Python (pip/uv) One version per environment. The resolver (pip's backtracking resolver, uv's PubGrub) must find a mutually compatible set or fail. Virtual environments isolate projects
.NET (NuGet) Lowest applicable version for direct requirements, nearest-wins for transitive ones; central package management (Directory.Packages.props). One version per assembly name, though AssemblyLoadContext can isolate
C / C++ No standard package manager. Conan, vcpkg, Bazel and system packages each differ. ABI matters as much as API, and the One Definition Rule makes two versions in one binary undefined behaviour (unless symbols are namespaced)
Zig build.zig.zon declares dependencies by URL and content hash. Each package's dependencies are explicit; duplicates are possible as separate modules

Why can Rust and Node have two versions when Java can't? Their compilers or loaders give each version a distinct identity (Rust mangles crate versions into symbol names; Node resolves require relative to each package's directory). Java's flat, name-keyed class path has one namespace. Isolation needs class loaders (OSGi, application servers, plugin systems) or shading/relocation.

Binary versus source compatibility

Java libraries must preserve binary compatibility (JLS chapter 13): code compiled against version N must link and run against version N+1 without recompiling. These changes break binary compatibility even though they may look harmless in source:

  • Removing or renaming a public method, field or class → NoSuchMethodError, NoSuchFieldError, NoClassDefFoundError.
  • Changing a method's parameter or return types (even void → boolean, or int → long) → NoSuchMethodError, because the descriptor is part of the linkage.
  • Changing a class to an interface or vice versa → IncompatibleClassChangeError.
  • Making a non-abstract method abstract, or adding an abstract method to an interface without a default → AbstractMethodError.
  • Changing static to instance or back.
  • Changing the value of a compile-time constant (public static final int MAX = 10): callers inlined the old value at compile time and keep using it silently until they recompile.

Tools: japicmp and Revapi compare two library versions and report binary and source incompatibilities. Use them in a library's CI. Semantic versioning (MAJOR.MINOR.PATCH) is the social contract: incompatible changes need a major bump. The Java ecosystem follows it unevenly.

Diagnosing and fixing conflicts

# Maven: who brings what, and which version won
$ ./mvnw dependency:tree -Dverbose -Dincludes=com.fasterxml.jackson.core
[INFO] com.shop:orders:jar:1.4.2
[INFO] +- com.acme:lib-a:jar:3.1:compile
[INFO] |  \- (com.fasterxml.jackson.core:jackson-databind:jar:2.15.4:compile - omitted for conflict with 2.19.0)
[INFO] \- com.acme:lib-b:jar:5.0:compile
[INFO]    \- com.fasterxml.jackson.core:jackson-databind:jar:2.19.0:compile
$ ./mvnw dependency:analyze            # used-but-undeclared and declared-but-unused dependencies
# Enforcer rules: fail the build on convergence problems
#   <dependencyConvergence/>, <requireUpperBoundDeps/>, <banDuplicateClasses/> (extra-enforcer-rules)

Fixes, in order of preference:

  1. Align versions with a BOM (jackson-bom, spring-boot-dependencies, netty-bom). It pins every module of a family to compatible versions, so jackson-core 2.19 doesn't end up with jackson-databind 2.15.
  2. Upgrade the library that drags in the old version.
  3. Declare the version explicitly in <dependencyManagement> (Maven) or as a constraint (Gradle).
  4. Exclude an unwanted transitive dependency (<exclusions>; Gradle exclude). Commonly used to remove duplicate logging bindings, such as commons-logging when using spring-jcl/jcl-over-slf4j, or the second SLF4J provider.
  5. Shade (libraries only), or isolate with class loaders (plugin systems).

Some conflicts aren't version conflicts at all but duplicate classes under different coordinates: javax.servlet:servlet-api versus jakarta.servlet:jakarta.servlet-api (different packages, so no clash, but a mixed setup won't work), or com.google.collections versus com.google.guava, which contain the same classes. The enforcer's banDuplicateClasses rule catches these.

Packaging across languages

What "a deployable" means elsewhere

Language Typical artifact Runtime dependencies
Java Executable JAR (+ JRE), container image, or GraalVM native binary A JVM, unless native
Go One statically linked binary (with CGO_ENABLED=0), trivially cross-compiled (GOOS=linux GOARCH=arm64 go build) None, so FROM scratch or distroless images of 10–20 MB are common
Rust A native binary (statically linked Rust crates; dynamically linked to libc by default; musl target for fully static builds) libc, unless musl
C / C++ Executables plus static (.a/.lib) or shared (.so/.dylib/.dll) libraries Shared libraries resolved by the dynamic loader at start-up (LD_LIBRARY_PATH, rpath, ldd to inspect); DLL hell is C's JAR hell, and symbol versioning in glibc mitigates it
Zig A native binary, easily static and cross-compiled to any target from any host (zig build -Dtarget=aarch64-linux-musl); ships libc headers for many targets None if static
C#/.NET Framework-dependent DLLs, self-contained single-file executables, or Native AOT binaries .NET runtime, unless self-contained or AOT
Python Wheels (.whl: prebuilt, possibly platform-specific with native extensions), sdists; deployed into a virtualenv or container A Python interpreter plus site-packages. "Works on my machine" issues often come from native wheels, hence manylinux tags
Node.js node_modules + source, or bundles (esbuild, ncc), or single-executable applications The Node runtime
Erlang/Elixir An OTP release (mix release) bundling the BEAM runtime (ERTS), compiled code and config, with hot code upgrades Included ERTS

The trend is the same everywhere: self-contained, immutable artifacts in container images, built reproducibly in CI (chapter 43, Part VIII). Java gets there with layered images, jlink runtimes, the AOT cache and native images. Go and Rust get there by default with static binaries.

Static versus dynamic linking

  • Static linking copies library code into the executable. You get one self-contained file, no run-time lookup surprises, and whole-program optimisation (LTO), at the cost of bigger binaries. Security fixes in a library require rebuilding every consumer, and LGPL obligations add complications.
  • Dynamic linking loads shared libraries at start-up or on demand (dlopen). Memory is shared between processes, and you can patch a library once system-wide. The costs are version mismatches (GLIBC_2.38 not found when a binary built on a new distro runs on an old one), LD_LIBRARY_PATH issues and ABI breaks.
  • ABI (Application Binary Interface): calling convention, struct layout, name mangling, and exception and RTTI format. C has a stable ABI per platform, which is why every language interoperates through C (chapter 39's FFM). C++ has no stable cross-compiler ABI (and changing std::string's layout in GCC 5 forced a dual ABI). Rust deliberately has no stable ABI (use extern "C" / #[repr(C)] at boundaries). Swift achieved ABI stability on Apple platforms. Java's equivalent of the ABI is bytecode binary compatibility, which is far more forgiving.

Lab: dependency conflicts and their fixes

Run with JDK 21 (and a JDK 25 runtime for the last experiment), using the two versions of the com.acme.money library from Start here: 1.0 has format and version; 2.0 changes format's output and adds formatWithGst.

Experiment 1: finding duplicate classes before they bite

Text
$ comm -12 <(unzip -Z1 money-1.0.jar | grep class$ | sort) <(unzip -Z1 money-2.0.jar | grep class$ | sort)
com/acme/money/Money.class

Any class present in two JARs on one classpath is a conflict waiting for a classpath reordering (a new dependency, a different build tool version, a different container base image) to change which one loads. Build-time checks automate this: Maven Enforcer's banDuplicateClasses rule, Gradle's duplicate-class detection in some plugins, or a simple script over the final artifact. Common real cases are the same library under two group ids (javax.* vs jakarta.* APIs, old commons-logging vs jcl-over-slf4j) that no version resolution can unify, because the build tool thinks they're different libraries.

Experiment 2: isolating versions with class loaders

Java
for (String jar : List.of("money-1.0.jar", "money-2.0.jar")) {
    URLClassLoader l = new URLClassLoader(new URL[]{Path.of(jar).toUri().toURL()}, ClassLoader.getPlatformClassLoader());
    Class<?> c = l.loadClass("com.acme.money.Money");
    … call version() and format() reflectively …
}
Text
money-1.0.jar → version 1.0, format Rs 123, loader URLClassLoader@1d082e88
money-2.0.jar → version 2.0, format ₹123.45, loader URLClassLoader@2ddc8ecb
same JAR, two loaders: same name true, same class false

Both versions lived in one JVM at once, because a class's identity is its name plus its defining class loader. That's how application servers isolate deployed apps, how plugin systems (IDEs, Jenkins, Elasticsearch) let plugins bring their own dependencies, and how OSGi works. The last line shows the price: the same class loaded by two loaders gives two distinct classes, so passing an object from one side to the other fails with the baffling ClassCastException: com.acme.money.Money cannot be cast to com.acme.money.Money. Isolation works when the boundary only shares types from a common parent loader (JDK types, a shared API JAR).

Experiment 3: shading (relocating a dependency)

When two parts of an application truly need incompatible versions, a build can relocate one of them into a private package. Done by hand here (the Maven Shade and Gradle Shadow plugins rewrite bytecode to do this automatically):

Java
package com.cafe.shaded.money;      // was com.acme.money, version 1.0
Text
legacy report uses shaded 1.0: Rs 123
new checkout uses 2.0: ₹129.62 incl. GST

Both versions now coexist on one classpath because they're different classes. Libraries shade dependencies to avoid inflicting their versions on users (many shade Guava, Netty or Jackson). Costs: larger JARs, duplicated code in memory, security fixes in the shaded copy that your scanners may not see, and reflection or service-loader files that the relocation can miss.

Experiment 4: depending on JDK internals

Java
var f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true);
var u = (sun.misc.Unsafe) f.get(null); long addr = u.allocateMemory(8); …
new sun.security.util.HexDumpEncoder();
Text
$ javac Old.java
Old.java:2: warning: Unsafe is internal proprietary API and may be removed in a future release
Old.java:4: error: package sun.security.util is not visible

$ jdeps --jdk-internals out
   Old  -> sun.misc.Unsafe                     JDK internal API (jdk.unsupported)
   Old  -> sun.security.util.HexDumpEncoder    JDK internal API (java.base)

$ java -cp out Old                       (JDK 21, compiled with --add-exports)
off-heap value 42
java.lang.IllegalAccessError: class Old (in unnamed module) cannot access class sun.security.util.HexDumpEncoder
(in module java.base) because module java.base does not export sun.security.util to unnamed module

$ java25 -cp out Old
WARNING: A terminally deprecated method in sun.misc.Unsafe has been called
WARNING: sun.misc.Unsafe::allocateMemory has been called by Old (file:/tmp/V3/c42/int/out/)
WARNING: sun.misc.Unsafe::allocateMemory will be removed in a future release
off-heap value 42

Since JDK 16–17 the JDK strongly encapsulates its internals: compiling against them needs --add-exports, and running needs it again (or --add-opens for reflection), otherwise IllegalAccessError or InaccessibleObjectException. sun.misc.Unsafe stays reachable through the jdk.unsupported module, but its memory-access methods are deprecated for removal and JDK 24+ prints a warning on first use (JEP 498); the replacements are VarHandle and the FFM API's MemorySegment. Old libraries are the usual culprits when an upgrade breaks: run jdeps --jdk-internals over all your JARs before upgrading, and upgrade or replace the libraries it flags.

Experiment 5: a trimmed runtime

Text
$ jdeps --print-module-deps cafe.jar money-2.0.jar
java.base
$ jlink -p mods --add-modules com.cafe --strip-debug --no-header-files --no-man-pages --output rt
$ du -sh rt                    → 52M          (full JDK 21: 286M)
$ rt/bin/java --list-modules   → com.acme.money, com.cafe, java.base@21.0.12.1

jdeps worked out that the app needs only java.base; jlink built a runtime containing just that plus the app's modules. A typical Spring Boot service needs a dozen or so JDK modules (java.sql, java.naming, java.management, jdk.crypto.ec…) and its runtime lands around 60–80 MB, against several hundred MB for a full JDK image. Non-modular apps can still use jlink for the JDK part, with the app's JARs on the classpath.

Try it yourself

  1. Add a third library that depends on money 1.0 and declare money 2.0 directly. Write the classpath Maven would build (nearest wins) and the one Gradle would build (highest wins). Which one runs formatWithGst correctly?
  2. Pass an object of experiment 2's Money class across loaders and reproduce the "cannot be cast to itself" ClassCastException.
  3. Rewrite experiment 4's off-heap code with Arena.ofConfined() and MemorySegment (final in JDK 22, so run it on JDK 25).
  4. Compare packaging in other ecosystems: go build (one static binary), cargo build --release, a Node app with npm ci and node_modules, and a Python wheel with its dependencies. Where does each store dependency versions, and how does each resolve conflicts?

Revision sheet: modules, packaging and dependency conflicts

Key ideas

  • Artifacts: JARs (classes, resources, manifest), coordinates (group:artifact:version), sources and javadoc JARs, WARs, repositories (Maven Central).
  • Finding classes: class loader delegation (bootstrap → platform → application); classpath order (first wins); module path with readability and exports; service loading (META-INF/services, provides/uses).
  • Executable JARs: Main-Class, Class-Path; fat/uber JARs (assembled or Spring Boot's nested-JAR loader); layered JARs for container caching.
  • Dependency conflicts: transitive dependencies; Maven nearest-wins vs Gradle highest-wins; BOMs and platforms for alignment; exclusions; dependency locking; duplicate classes; relocation (shading); class loader isolation.
  • Errors to recognise: NoClassDefFoundError, ClassNotFoundException, NoSuchMethodError, NoSuchFieldError, AbstractMethodError, IncompatibleClassChangeError, LinkageError, ClassCastException between same-named classes.
  • JPMS: module-info (requires, exports, opens, provides, uses), strong encapsulation of JDK internals, --add-exports/--add-opens, automatic modules, jdeps, jlink.
  • Across languages: Go modules (minimal version selection, static binaries), Cargo (semver, lock files, multiple major versions coexisting), npm (nested node_modules, lock files), Python wheels and virtual environments, .NET NuGet (nearest wins), C/C++ (package managers like vcpkg and Conan, ABI concerns).

Numbers to remember

  • Lab: a jlinked runtime for a small app was 52 MB vs 286 MB for the full JDK.

Pitfalls

  • Trusting that the compile classpath equals the run-time classpath.
  • Ignoring duplicate classes and same-library-different-coordinates (javax vs jakarta).
  • Fat JARs that merge META-INF/services files incorrectly (lost service registrations).
  • Shading without relocating reflection strings and resources; unpatched shaded copies.
  • Depending on JDK internals; upgrading the JDK without running jdeps --jdk-internals.
  • Version ranges and unlocked dependencies producing different builds from the same source.

Glossary

  • Transitive dependency: a dependency of a dependency.
  • BOM: bill of materials, a curated set of aligned versions.
  • Shading/relocation: copying a dependency into your artifact under a renamed package.
  • Split package: one package spread over two modules or JARs.
  • Automatic module: a plain JAR on the module path, named from its manifest or file name.
  • Minimal version selection: Go's rule of using the lowest version that satisfies all requirements.