Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·42

Modules & Packaging

Exercises for Volume 3, chapter 42: JAR, WAR and EAR artifacts; the class path and the module path; JPMS in practice, jlink and jpackage; executable, fat and uber JARs; shading and relocation; why dependency conflicts happen and how resolution works; binary versus source compatibility; diagnosing and fixing conflicts; and packaging, static and dynamic linking in other languages. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~16 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The exercises follow the same four sets and the same locking as earlier chapters. Code is Java 21, with a JDK 25 runtime and Go for comparison. Every quoted output is real, and four of them catch experienced developers:

  • P1. The library changed int paise(String) to long paise(String). The caller, written as long p = Money.paise("123"), recompiled without a change: it was source compatible. But a caller compiled against 1.0 failed at run time on 2.0 with NoSuchMethodError: 'int com.acme.Money.paise(java.lang.String)', because the change was binary incompatible.
  • P3. Two JARs each contributed a payment provider through META-INF/services. Unzipped side by side into a naive fat JAR, the second file overwrote the first, and ServiceLoader found only [card] instead of [upi, card].
  • P4. Two modules exporting the same package x didn't even get the JVM started: LayerInstantiationException: Package x in both module a and module b.
  • P6. One multi-release JAR printed "base implementation" on JDK 21 and "versions/25 implementation" on JDK 25.

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • the duplicate Money.class across two JARs;
  • two class loaders giving "same name true, same class false";
  • shading letting 1.0 and 2.0 coexist;
  • sun.* internals refused at compile time;
  • a jlinked runtime of 52 MB against the full 286 MB JDK.

Coverage map.

Chapter component Exercises
JAR files; manifests; WAR and EAR T1, P2
the class path; NoClassDefFoundError vs ClassNotFoundException T2, P2
the module path and JPMS in practice; split packages T3, P4
jlink and jpackage T3, P8
executable, fat and uber JARs; service files T4, P3
shading and relocation T4, P5
why conflicts happen; how resolution works T5, P7
binary vs source compatibility T6, P1
diagnosing and fixing conflicts T7, P7
multi-release JARs T6, P6
packaging across languages; static vs dynamic linking T8, P9
container images T9, P8

Theory

T1. Artifacts: JAR, WAR, EAR and the manifest

  1. A JAR is a ZIP file. What does it contain? - classes and resources; - META-INF/MANIFEST.MF, with Main-Class, Class-Path, Multi-Release, Automatic-Module-Name, Implementation-Version and Add-Opens; - META-INF/services; - META-INF/versions/N (P6); - signatures.

Which manifest attributes does a backend team actually use? 2. WAR and EAR files. What's in a WAR (WEB-INF/classes, WEB-INF/lib, web.xml)? How do application servers isolate class loaders? Why did the industry move from "deploy a WAR to a shared Tomcat or WebSphere" to "ship an executable JAR or container image"? When are WARs still used? 3. Spring Boot's executable JAR layout: BOOT-INF/classes, BOOT-INF/lib, the launcher, layers.idx, and jarmode=tools extract. Why does Boot nest JARs instead of flattening them, and what does layering do for container images?

T2. The class path, and when classes can't be found

  1. Explain class path semantics: - an ordered list of directories and JARs; - the first match wins; - no versions; - no notion of "which JAR needs which".

Why is that a source of "it works on my machine" bugs? The lab's duplicate Money.class is the canonical case. 2. Distinguish: - ClassNotFoundException: an explicit lookup (Class.forName, a class loader) didn't find the class; - NoClassDefFoundError: a class used at compile time is missing at run time, or failed initialisation (ch40's P2); - NoSuchMethodError and NoSuchFieldError: the class is there but a different version (P1); - IncompatibleClassChangeError, AbstractMethodError and LinkageError: "loader constraint violation", for duplicate classes in different loaders (ch40's P3).

For each, give the most likely cause and the first diagnostic command. 3. Name the tools that show what's on the class path and where a class came from: - -verbose:class or -Xlog:class+load (it prints the JAR each class came from); - ClassLoader.getResource("com/acme/Money.class"); - mvn dependency:tree; - gradle dependencies and dependencyInsight; - jdeps.

  1. The module path. Explain reliable configuration (missing modules fail at startup), strong encapsulation (P4's split packages are forbidden; non-exported packages are invisible), and the readability graph. P4's two modules exporting x failed with LayerInstantiationException: Package x in both module a and module b. Why does JPMS forbid split packages, and how does that affect libraries that put classes in the same package across JARs (common in old Java EE APIs and some test utilities)?
  2. Application modules in practice. Should TiffinBox's services use module-info.java? Weigh what it gives (enforced boundaries, jlink with your own modules, no accidental internal use) against the friction (Spring's reflection needing opens, test frameworks and patching modules, libraries without descriptors, automatic module names changing). What alternatives enforce boundaries (package-private visibility, ArchUnit, Spring Modulith, multi-module builds)?
  3. jlink and jpackage. The lab's 52 MB runtime against the 286 MB JDK. Explain which modules a Spring Boot application typically needs (jdeps --print-module-deps plus what it misses: jdk.crypto.ec, java.naming, jdk.management, jdk.unsupported), and what jpackage produces (native installers with a runtime). When would a backend use jpackage?

T4. Fat JARs, uber JARs, service files and shading

  1. Compare the ways to make a single deployable: - a thin JAR plus a lib/ directory (Class-Path in the manifest); - a nested fat JAR (Spring Boot); - an uber JAR, merged by unpacking all dependencies (Maven Shade, Gradle Shadow).

What breaks when merging? P3 showed the META-INF/services overwrite. Also consider META-INF/spring.factories and AutoConfiguration.imports, module-info.class from several JARs, signature files making the JAR invalid, LICENSE and NOTICE files, and duplicate classes. 2. Shading and relocation. The lab ran shaded 1.0 alongside 2.0, with com.acme.money rewritten to tb.shaded.money. When should a library shade (to avoid imposing a dependency version on its users)? When should an application avoid it? What goes wrong: - reflection with string class names; - service files not rewritten; - security scanners missing shaded copies; - larger artifacts; - debugging stack traces with relocated names. 3. Write the Maven Shade configuration fragments that fix P3's problem (ServicesResourceTransformer, AppendingTransformer for other files) and relocate a dependency safely.

T5. Why dependency conflicts happen and how resolution works

  1. Explain transitive dependencies and the diamond problem. TiffinBox depends on payments-sdk (needs Jackson 2.15) and maps-client (needs Jackson 2.17), and only one Jackson can be on the class path. Why can't Java load both (outside shading and separate loaders: the lab)?
  2. Compare the resolution strategies: - Maven: "nearest wins", then first declaration; dependencyManagement; BOMs. - Gradle: the highest version wins by default; rich versions (strictly, require, prefer); constraints; platforms; resolution strategies. - npm: a nested tree, so several versions coexist (Volume 2). - Go: minimal version selection. - Cargo: semver-compatible unification, and several major versions coexist.

Which ones can produce "the version I resolved is older than one of my dependencies needs"? 3. What are BOMs (spring-boot-dependencies, jackson-bom) and dependency platforms? Why does a Spring Boot project usually let the BOM pick versions, and what's the risk of overriding one version (jackson.version) independently of the rest?

T6. Binary versus source compatibility, and multi-release JARs

  1. Define source compatibility (callers still compile) and binary compatibility (callers compiled against the old version still link and run). P1's int paise(String) → long paise(String) was source compatible but binary incompatible (NoSuchMethodError: 'int com.acme.Money.paise(java.lang.String)'), because the JVM links by exact descriptor including the return type. Classify each of these as source and binary compatible or not: - adding a method; - adding a default method to an interface; - adding an abstract method to an interface; - widening a parameter type; - changing a return type; - making a method static; - adding a checked exception; - changing a constant's value (ch40's inlining); - adding an enum constant; - removing a method.
  2. Explain why library authors care about binary compatibility more than application developers. Then cover semantic versioning (what major, minor and patch promise), and tools that check it (japicmp, Revapi, the Gradle and Maven plugins).
  3. Multi-release JARs. P6's JAR printed "base implementation" on 21 and "versions/25 implementation" on 25. Explain how META-INF/versions/N selection works, why the versioned class must have the same public API, and where MR-JARs appear in your dependencies (Jackson, Log4j, ByteBuddy) and in debugging ("which class actually ran?").

T7. Diagnosing and fixing conflicts

  1. Write the diagnostic procedure for a production NoSuchMethodError in com.fasterxml.jackson.databind…:
  2. find which JAR supplied the class (-Xlog:class+load or getCodeSource);
  3. find which version the caller was compiled against;
  4. run mvn dependency:tree -Dverbose -Dincludes=com.fasterxml.jackson.core, or gradle dependencyInsight;
  5. find why the older version won;
  6. choose a fix.
  7. Compare the fixes: - align with a BOM; - an explicit dependencyManagement pin; - exclusions; - upgrading the dependency that needs the old version; - shading (as the library); - isolating in a separate class loader or a separate service.

Which is the default, and which is a last resort? 3. Prevention: - Maven Enforcer rules (dependencyConvergence, requireUpperBoundDeps, banDuplicateClasses, banDuplicatePomDependencyVersions); - Gradle's failOnVersionConflict and dependency locking; - Dependabot or Renovate with grouped updates; - SBOM generation (CycloneDX) and vulnerability scanning.

Write the build policy.

T8. Packaging across languages; static and dynamic linking

  1. What is "a deployable" in other ecosystems? - Go: a single static binary (P9: 2.2 MB, "not a dynamic executable" with CGO_ENABLED=0). - Rust: a binary, statically linked against Rust crates and dynamically against libc by default, or fully static with musl. - Node: source plus node_modules, or a bundled file plus the runtime. - Python: wheels plus a virtualenv, or a container. - .NET: a framework-dependent DLL, or self-contained or NativeAOT.

What does each require on the target machine? 2. Static against dynamic linking. P9: enabling cgo and importing net produced a binary linked against libc.so.6 and ld-linux. What are the trade-offs? - portability (static runs on scratch images; dynamic needs a matching libc: glibc against musl in Alpine); - security updates (a static binary must be rebuilt to fix a vulnerability in linked code; with dynamic linking the OS library is updated); - size; - DNS and locale behaviour (Go's pure resolver against cgo). 3. Compare the JVM's situation (bytecode plus a runtime: the JDK or a jlinked runtime; native libraries in JARs for Netty's epoll or SQLite JDBC) and GraalVM native-image, which produces a native binary (static or mostly static, with --static --libc=musl).

T9. Container images for JVM services

  1. Design the TiffinBox service image: - base image choice (distroless/java, Eclipse Temurin JRE slim, a jlinked runtime on distroless/base, or Alpine with a musl JDK); - layered JAR extraction (T1); - a non-root user; - JVM flags (ch40's S1); - health checks; - multi-arch builds.

Write the Dockerfile. 2. Image size and security. Compare the full JDK image (about 400 MB), a JRE (about 200 MB), a jlinked runtime (the lab's 52 MB plus app), distroless, and native-image (about 50–100 MB). Which attack-surface items matter: shells, package managers, javac, setuid binaries? How do you scan images (Trivy, Grype)? 3. Reproducible builds and provenance. Cover deterministic JARs (fixed timestamps: project.build.outputTimestamp), SBOMs inside images, image signing (cosign), and why "the same commit gives the same image digest" matters for incident response and supply-chain security.

Programming exercises

P1. Binary versus source compatibility

Build library 1.0 (int paise(String), String fmt(int)) and 2.0 (long paise(String), and an added fmtWithGst). Show: - an app compiled against 2.0 failing on 1.0 with NoSuchMethodError for both methods; - an app compiled against 1.0 recompiling fine against 2.0 (source compatible) but failing when run uncompiled against 2.0 (binary incompatible).

Then make 2.0 binary compatible by keeping the old method and adding a new name, and set up japicmp to catch the break.

P2. Class path errors, deliberately

Produce each of these, with a one-line cause and the command that diagnoses it: - ClassNotFoundException (Class.forName with a missing JDBC driver); - NoClassDefFoundError (a compile-time dependency removed at run time); - NoSuchMethodError (P1); - AbstractMethodError (an interface gains a method, with an old implementation); - IncompatibleClassChangeError (an instance method becomes static).

Use -Xlog:class+load to show which JAR supplied a class.

P3. Fat JARs and service files

Create an SPI (PaymentProvider) and two provider JARs (upi, card), each with META-INF/services/tb.PaymentProvider. Show: - ServiceLoader finding both with separate JARs; - a naive uber JAR (unzipped on top of each other) finding only one; - the fix: a merged services file (by hand, then with Maven Shade's ServicesResourceTransformer or Gradle Shadow's mergeServiceFiles).

Then check the same problem for Spring Boot's AutoConfiguration.imports.

P4. JPMS: split packages, exports and opens

Create these module failures and fix each: - two modules exporting the same package (LayerInstantiationException); - a module using a non-exported package (a compile error); - reflection into a non-opened package (InaccessibleObjectException, ch39's P5); - a missing requires (the module not found at startup).

Then modularise a small TiffinBox library (money) with module-info and Automatic-Module-Name for consumers on the class path.

P5. Shading two versions side by side

Reproduce the lab's shading of money 1.0 to tb.shaded.money, so a legacy report uses 1.0 while checkout uses 2.0. Then demonstrate three relocation pitfalls: - a class name in a properties file (formatter=com.acme.money.Money) not rewritten; - a services file not rewritten without the transformer; - a security scanner not seeing the shaded copy.

Fix each.

P6. A multi-release JAR

Build a JAR whose root Ver.class prints "base implementation" and whose META-INF/versions/25/Ver.class prints the 25 implementation. Run it on JDK 21 and JDK 25. Then show: - jar --release rejecting a versioned class with an extra public method; - -Xlog:class+load revealing which entry was loaded.

Discuss a realistic use (virtual threads on 21+ with a platform-thread fallback for 17).

P7. Diagnose and fix a dependency conflict

Build a Maven or Gradle project, or simulate the resolution by hand, where: - payments-sdk needs Jackson 2.15; - maps-client (deeper) needs 2.17; - nearest-wins picks 2.15, and the maps code throws NoSuchMethodError.

Diagnose it with dependency:tree -Dverbose. Fix it with a BOM import, and add the Enforcer rules requireUpperBoundDeps and banDuplicateClasses. Then add a javax.annotation/jakarta.annotation duplicate and catch it with banDuplicateClasses.

P8. A minimal runtime and container image

Run jdeps --print-module-deps on a small HTTP service, jlink a runtime, and measure its size against the full JDK. Then: - add jdk.localedata and show that NumberFormat for hi-IN fails to produce Hindi formatting without it; - write the Dockerfile from T9 for the service, and compare the image sizes for a JDK base, a JRE base and jlink plus distroless (expected values if Docker is unavailable).

P9. Static and dynamic binaries in Go; packaging elsewhere

Build the same Go program with CGO_ENABLED=0 and with cgo enabled plus net. Compare file and ldd output and the sizes. Then: - run the static one in an empty directory (simulating a scratch image); - explain why the dynamic one would fail on Alpine; - write the packaging steps for a Python service (wheels, virtualenv, a slim image) and a Node service (npm ci --omit=dev, or a bundle).

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–42)

C1. Publish TiffinBox's shared libraries properly

Package the shared money, result and events libraries (ch33–ch37) for use by all services. Give them: - semantic versioning; - Automatic-Module-Name (or module-info); - binary-compatibility checks with japicmp; - a BOM (tiffinbox-platform-bom) that pins them with Spring Boot's BOM; - reproducible builds; - an SBOM; - a changelog.

Publish 1.0, make a compatible 1.1 and an incompatible 2.0, and show which checks pass or fail.

Combines: Volume 1's version control and release practices, Volume 2's package publishing (ch30), ch33–ch37's libraries, ch36's generic API rules, and this chapter.

C2. An image and dependency hygiene pipeline

For the order service, set up: - Maven Enforcer (or Gradle equivalents) with upper bounds, duplicate classes and Java version rules; - Renovate with grouped Spring Boot updates; - layered Boot JAR extraction; - a jlinked distroless image built for amd64 and arm64; - Trivy scanning with a policy; - cosign signing and an SBOM attestation; - a Kubernetes admission policy requiring signed images.

Measure the image size and the scan findings before and after.

Combines: Volume 2's CI/CD and deployment (ch30, ch31), ch39's JDK upgrade pipeline, ch40's JVM flags, and this chapter.

C3. Migrate a WAR deployed on a shared application server

A legacy TiffinBox admin application is a WAR on a shared Tomcat 9 with three other WARs. It uses javax.servlet, has a WEB-INF/lib with 120 JARs (some duplicated with Tomcat's lib/), and leaks memory on redeploy. Plan and execute its migration to an executable Spring Boot JAR in its own container. Cover: - the javax → jakarta change; - the class path clean-up (duplicates, conflicts); - fixing the leak sources (ch40's P3); - configuration externalisation; - parallel running during cut-over.

Combines: Volume 1's migration practices, ch39's upgrade tooling, ch40's class-loader leaks, and this chapter.

What the chapter leaves out

Dependency scopes and their run-time meaning

Maven's compile, provided, runtime, test, system and import scopes, and Gradle's implementation, api, compileOnly and runtimeOnly, decide what ends up on which class path: - provided/compileOnly (servlet API, Lombok) aren't packaged, causing NoClassDefFoundError if the runtime doesn't supply them (P2); - runtime/runtimeOnly (JDBC drivers) aren't visible at compile time; - Gradle's api against implementation controls what leaks to consumers' compile class paths, which affects compile speed and accidental coupling.

Chapter 43 covers it.

Plugin architectures and class-loader isolation

Applications that load third-party plugins need isolated class loaders, defined APIs, and careful sharing of common libraries: - Jenkins, IntelliJ, Elasticsearch and Kafka Connect do this; - PF4J is a lightweight Java plugin framework; - OSGi is the heavyweight standard.

Plugins make version conflicts survivable and introduce the identity problems of ch40's P3. Avoid building plugin systems unless you truly need third-party extensions.

Software supply-chain security

Beyond scanning: - dependency confusion (an internal package name published publicly); - typosquatting; - compromised maintainers (the xz backdoor in 2024 was in a C library); - build-system compromise.

The defences are repository managers with allowlists (Nexus, Artifactory), pinned checksums (Gradle's dependency verification verification-metadata.xml), reproducible builds, SLSA provenance, and signing (Sigstore). Treat your dependency graph as part of your attack surface.

Licensing and compliance

Every dependency has a licence: - Apache-2.0 and MIT are permissive; - GPL and AGPL are copyleft with obligations; - some carry "commons clause" or BSL-style restrictions (ch38's Akka note).

Shading and fat JARs distribute dependencies and their licence terms. Generate licence reports (the license-maven-plugin, CycloneDX's licence data), keep NOTICE files merged (T4), and have a policy for which licences are allowed.

Native and platform-specific artifacts

Libraries with native code publish classifier JARs per platform (netty-transport-native-epoll:linux-x86_64, linux-aarch_64), and building multi-arch images must pull the right ones. Apple Silicon development machines and arm64 cloud instances (Graviton) make this common. Test images on every target architecture, because a missing native classifier silently falls back to slower pure-Java paths (Netty's NIO instead of epoll), or fails.

Senior exercises

S1. The packaging and dependency policy for the organisation

Write the policy: - artifact types (executable Boot JARs in containers; WARs only for legacy); - BOMs and platforms; - conflict rules (Enforcer, locking); - shading rules (libraries only, with SBOM disclosure); - binary-compatibility checks for internal libraries; - image standards (base, jlink, non-root, multi-arch, signing); - SBOMs; - the update cadence; - licence policy.

Tie each rule to an output from this chapter.

S2. Review a build change

A PR to the order service: - switches from Spring Boot's plugin to Maven Shade "for a simpler JAR"; - adds jackson-databind 2.18 directly to fix a CVE while the Boot BOM manages 2.17; - excludes commons-logging from three dependencies without adding a bridge; - adds <scope>provided</scope> to the PostgreSQL driver "because it's in the base image"; - sets Class-Path: lib/* in the manifest.

Write the review.

S3. Decide on a shared-library strategy

TiffinBox has 14 services, each with copied utility code (money, errors, logging setup, HTTP client configuration). One team proposes a single tiffinbox-commons JAR used by all. Another proposes several small libraries. A third proposes no shared code at all ("microservices should not share"). Decide, covering coupling, versioning, release cadence, binary compatibility and the BOM.

S4. Teach "why your JAR worked yesterday" with four outputs

Prepare a 15-minute session using four outputs: - the lab's duplicate Money.class and two loaders; - P1's source-compatible but binary-incompatible change; - P3's lost service provider; - P4's split-package startup failure.

End with three rules and the tools that enforce them.

S5. Plan a "log4shell-style" response capability

Design how TiffinBox would answer, within one hour of a critical CVE disclosure in a transitive Java library: - "which running services contain the vulnerable version?"; - "are any shaded copies affected?"; - "which images must be rebuilt?"; - "what's the fastest safe mitigation?"

Cover SBOMs per image digest, an inventory of running digests, shaded-dependency detection, mitigation options (a version override through the BOM, JVM flags or configuration, WAF rules), the rollout, and the communication.