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

Workbench / Volume 3 Exercises: The Backend

V3·39

Modern Java through JDK 27

Exercises for Volume 3, chapter 39: the release train, JEPs and preview features; var, switch expressions, text blocks, records, sealed types and pattern matching; flexible constructor bodies, compact source files and what happened to string templates; sequenced collections and other API additions; the Foreign Function & Memory API; the module system; runtime, GC and startup changes; deprecations and removals; and tracking change as a working engineer. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

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

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code is compiled with JDK 21. The same class files were also run on a JDK 25 runtime, which has no javac on this machine, to see what changed. Every quoted output is real, and four of them are worth knowing about before you start:

  • P1. One switch handled null, nested record patterns with a guard (Line(var d, var q, Upi(var vpa)) when q > 3), strings with guards and a default, without a single cast.
  • P3. list.reversed() is a view. Writing pongal into the reversed list changed the original list's last element.
  • P5. The same class file ran System.setSecurityManager(null) normally on JDK 21 and threw UnsupportedOperationException on JDK 25. Thread.stop() threw on both.
  • P6. -XX:-ZGenerational printed "Ignoring option ZGenerational; support was removed in 24.0" on JDK 25. JDK 21's ZGC reported "Using legacy single-generation mode", and JDK 25's printed young- and old-generation workers.

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

  • javac --release 8 rejecting List.of;
  • UnsupportedClassVersionError for a too-new class file;
  • the exhaustive-switch error after adding a sealed subtype;
  • compact object headers (24 → 16 bytes per Point);
  • startup times of 622, 585 and 498 ms (JDK 21, JDK 25, and JDK 25 with an AOT cache).

Coverage map.

Chapter component Exercises
the release train; LTS; JEPs and previews; other languages T1, P7
var T2, P2
switch expressions; pattern matching (type, record, guards, null) T3, P1
text blocks T2, P2
records; sealed types T3, P1
flexible constructor bodies; compact source files; string templates' withdrawal T4, P8
sequenced collections; other API additions T5, P3, P4
Foreign Function & Memory API T6, P9
concurrency recap (virtual threads, structured concurrency, scoped values) T5
JPMS in brief; strong encapsulation T7, P5
JVM, GC and performance changes; startup T8, P6
deprecations and removals; tracking change T9, P5, P7

Theory

T1. How Java evolves

  1. Explain the six-month release train, LTS releases every two years (17, 21, 25; 27 is a non-LTS feature release), vendor support windows, and why many companies upgrade only between LTS releases. What does a backend team lose by staying on 17 when 25 is out?
  2. Explain the JEP process: candidate, proposed to target, targeted, integrated. Then explain incubator modules (jdk.incubator.*) and preview features (--enable-preview, class files that only that exact release can run). Use string templates as the cautionary tale: they were previewed in 21 and 22, then withdrawn in 23.
  3. Compare how other languages evolve. Python uses PEPs on a yearly cadence and has deprecation periods. Go keeps a strict compatibility promise and uses go.mod's go directive. Rust has editions, so crates on different editions interoperate. C# releases yearly. Kotlin has stable, beta and experimental annotations. What does Java's approach optimise for?

T2. var and text blocks

  1. var (JDK 10) infers types for local variables. When does it improve readability (var orders = new ArrayList<Order>(), long generic types, loop variables), and when does it hurt (var x = service.process(), numeric literals, the diamond inferring Object; ch36's P1)? Where is var not allowed (fields, parameters, return types, null initialisers, array initialisers)?
  2. Text blocks (JDK 15). P2's output was Hello,·⏎··TiffinBox·user⏎total:·₹180⏎. Explain each part: incidental indentation stripped relative to the closing delimiter; trailing spaces stripped unless written as \s; \ at a line end joining lines; the trailing newline; and .formatted(…).
  3. Where do text blocks belong in backend code (SQL, JSON test fixtures, templates in tests), and why must you still never build SQL or JSON by string formatting from user input?

T3. Records, sealed types and pattern matching together

  1. Trace P1's switch:

    Java
    case null -> …
    case Line(var d, var q, Upi(var vpa)) when q > 3 -> …
    case Line(var d, var q, Card(var l4, var net)) -> …
    case Line l -> …
    case String s when s.isBlank() -> …
    case String s -> …
    default -> …
    

It printed bulk UPI order of 5 idli from asha@okicici, 1 dosa on RuPay ••4242, other line vada, null input, blank string and something else: Integer. Explain the order of evaluation, the dominance rules (why case Line l must come after the more specific Line(...) patterns), and how guards affect exhaustiveness. 2. Explain "data-oriented programming": records for data, sealed interfaces for alternatives, and pattern matching for behaviour (ch34's T5, ch37's T9). Show the Java 8 version of P1 (an instanceof chain with casts and a "unknown" fallback) and list the bugs that the modern version makes compile errors (the lab). 3. Which features are coming next? Primitive types in patterns (a preview in JDK 23 to 25), derived record creation (with expressions, still a JEP), and deconstruction patterns for classes. How should a team prepare without using previews?

T4. Flexible constructor bodies, compact source files and string templates

  1. Flexible constructor bodies (JEP 513, final in 25) allow statements before super(...) or this(...), as long as they don't use this. Rewrite a constructor that validates an argument before calling super. What did people do before (static helper methods called inside super(check(x)))? How does this help with ch34's P1 constructor hazard?
  2. Compact source files and instance main methods (JEP 512, final in 25): void main() { IO.println("Hello"); } with no class declaration and automatic imports of java.base. Who is this for (teaching, scripts), and what does it mean for small backend tools and ops scripts compared with Python or jshell?
  3. Explain why string templates were withdrawn. What problem were they solving (safe interpolation through processors, such as SQL with parameters and JSON with escaping)? What do you use instead (formatted, MessageFormat, query builders such as jOOQ, PreparedStatement)?

T5. Sequenced collections and API additions

  1. Sequenced collections (JDK 21) add getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed() to lists, deques, sorted sets and linked hash sets and maps, plus putFirst, putLast, firstEntry and pollFirstEntry on maps. P3 showed: - reversed() is a writable view: writing through it changed the original; - LinkedHashMap.putFirst and putLast produced {a=1, b=2, c=3}; - reversed() on the map gave {c=3, b=2, a=1}; - an empty list's getFirst() threw NoSuchElementException.

Which old idioms do these replace? What compatibility issue did adding getFirst to List cause for some libraries (Kotlin's extension functions of the same name)? 2. P4's small API additions: - Math.clamp(150, 0, 100) → 100; - StringBuilder.repeat("ab", 3) → ababab; - "idli+vada-dosa".splitWithDelimiters("[+-]", 0) → [idli, +, vada, -, dosa]; - Character.isEmoji(🍛) → true; - HexFormat.formatHex → cafe.

Add others worth knowing: String.strip/isBlank/lines/indent, Stream.toList, Collectors.teeing, Files.mismatch, HttpClient, InstantSource, RandomGenerator, Optional.isEmpty, and Duration and Instant helpers. For each, give the hand-written code it replaces in TiffinBox. 3. Recap the concurrency features from ch38: virtual threads (21), the synchronized pinning fix (24), structured concurrency (preview), and scoped values (final in 25). Which JDK version should a new service target, and why?

T6. The Foreign Function & Memory API

  1. The FFM API (final in JDK 22) has several parts: Linker, SymbolLookup, FunctionDescriptor, MethodHandle downcalls, Arena lifetimes, MemorySegment and ValueLayout. Why does it replace JNI (C glue code, crashes, manual memory management) and sun.misc.Unsafe off-heap access (now deprecated for removal, JEP 471)?
  2. When would a TiffinBox backend use FFM? Possibilities include calling a native image library, a fast hashing library (xxHash), the OS (getpid or sysconf), or mapping a large file off-heap. When should you choose a pure-Java library or a separate process instead?
  3. What are the risks? Native code can crash the JVM; there's the --enable-native-access warning and its future default; virtual-thread pinning in native frames (ch38); and portability across OS and CPU. How does jextract help?

T7. The module system and strong encapsulation

  1. JPMS in brief: module-info.java (requires, exports, opens, provides/uses), the module path against the classpath, automatic modules, and the unnamed module. Why do most Spring Boot applications still run on the classpath, while the JDK itself is fully modular?
  2. Strong encapsulation of JDK internals (default-deny since 16, with --illegal-access removed in 17). P5's setAccessible on String.value failed with "module java.base does not "opens java.lang"". Which libraries hit this (old Lombok, older Mockito, serialisation libraries, some APM agents), and how do you fix them (upgrade, use --add-opens as a temporary bridge, or jdeps --jdk-internals to find them)?
  3. What does jlink give you (a custom runtime image containing only the modules you need), and what are the size and attack-surface benefits for containers (ch42)?

T8. Runtime evolution: GC, startup and memory

  1. Trace GC defaults and options across releases: - G1 has been the default since 9 (P6: "Using G1" on both 21 and 25); - ZGC was single-generation on 21 by default (P6: "Using legacy single-generation mode"); - generational ZGC is the only mode on 24+ (P6: young- and old-generation workers; -XX:-ZGenerational ignored); - Shenandoah gained a generational mode; - Serial and Parallel GC are still there.

When would a TiffinBox service choose ZGC over G1? 2. Startup and warm-up: CDS (class data sharing), AppCDS, and the JDK 24–25 AOT cache (the lab: 622 ms → 498 ms; Spring Boot reportedly 40%+ faster), CRaC (checkpoint and restore in some distributions), and GraalVM native-image. Compare startup time, peak throughput, memory, build complexity and the closed-world constraints. 3. Memory: compact object headers (the lab: 24 → 16 bytes per small object, opt-in in 25), container awareness (the JVM reads cgroup limits; -XX:MaxRAMPercentage), and Valhalla's future value objects. Estimate the heap saved for a service holding 10 million small objects.

T9. Deprecations, removals and tracking change

  1. Classify the removals and deprecations a backend upgrade from 8 or 11 to 25 meets: - Removed: Java EE modules (JAXB, JAX-WS) in 11, Nashorn in 15, RMI activation, the Applet API, and the Security Manager permanently disabled in 24 (P5: UnsupportedOperationException on 25). - Deprecated for removal: finalization, Thread.stop (throws since 20; P5), Unsafe memory access, and the boxed-primitive constructors (new Integer(5) still ran on 25; P5). - Behaviour changes: UTF-8 by default (JDK 18), stricter TLS defaults, and changes to Locale data.
  2. P7: jdeprscan on an old JAR listed Object::finalize() overridden (forRemoval=true), Integer::<init>(I)V (forRemoval=true), Date::<init>(III)V, Runtime::runFinalization()V (forRemoval=true) and Thread::stop()V (forRemoval=true). Build an upgrade checklist around jdeprscan, jdeps, javac -Xlint:all, OpenRewrite recipes and running the test suite on the new JDK in CI.
  3. How should a working engineer track change? Consider JEP pages, release notes, the inside.java and Java YouTube channels, early-access builds in CI, Quality Outreach for libraries, and the "Java Almanac" diffs. Design a lightweight quarterly routine for the team.

Programming exercises

P1. Pattern matching over records and sealed types

Write P1's describe(Object) with null, nested record patterns, guards, strings and a default, and check each branch. Then: - write fee(Pay) over the sealed Pay without a default; - add a Wallet type and capture the compiler error; - move case Line l above the record patterns and capture the dominance error; - rewrite everything Java 8-style and count the casts.

P2. var and text blocks

Write the P2 text block, show its exact output with visible spaces and newlines, and explain each escape. Then: - show three bad uses of var (an int accumulator that overflows, new ArrayList<>(), an unreadable var x = svc.run()) and fix them; - write a SQL text block with bind parameters for "ready orders of a kitchen in the last hour", and a test that would catch someone replacing the parameters with formatted.

P3. Sequenced collections

Show these behaviours: - getFirst, getLast, and reversed() as a writable view; - LinkedHashMap.putFirst/putLast/firstEntry/reversed; - an empty getFirst throwing.

Then refactor five old idioms in a sample class to the sequenced methods, and decide where a view is dangerous and a copy is needed (returning reversed() from a getter).

P4. Small API additions that remove utility code

Use these and write the "before" code each one replaces in TiffinBox: - Math.clamp; - StringBuilder.repeat; - splitWithDelimiters; - Character.isEmoji; - HexFormat; - String.indent/stripIndent; - Files.mismatch; - InstantSource; - HttpClient with a timeout.

Delete an internal StringUtils class's methods that the JDK now covers, and count the lines removed.

P5. What breaks across JDK versions

Compile one class with JDK 21 (--release 21) that calls Thread.stop(), System.setSecurityManager(null), new Integer(5) and reflective access to String.value. Run it on JDK 21 and JDK 25, record the differences, and write the migration for each call.

P6. GC defaults and flags across JDKs

On JDK 21 and JDK 25, print which GC is selected by default, ZGC's mode, and what happens with -XX:-ZGenerational. Then: - run the same allocation-heavy program (ch35's 1 million map entries in a loop) with G1 and ZGC on both JDKs, logging GC pauses with -Xlog:gc; - compare the maximum pause and the throughput; - write the flags you'd ship for a 2 GB API container.

P7. An upgrade audit with jdeprscan and jdeps

Build an old-style JAR using: - new Integer; - the deprecated Date constructor; - runFinalization; - Thread.stop; - a finalize() override; - sun.misc.Unsafe.

Run jdeprscan --release 21 and jdeps --jdk-internals. Then write the remediation table, and an OpenRewrite configuration (rewrite.yml) that applies the Java 21 migration recipe.

P8. Constructors and scripts in JDK 25

On JDK 25 (or a JDK 25 compiler if available): - rewrite a constructor that validates before super() using flexible constructor bodies, and assign a field in the prologue so a superclass's overridden-method call sees it; - write a compact source file, void main(), that reads a JSON health endpoint with HttpClient and prints the status; - compare it with the equivalent Python script.

P9. Calling native code with FFM

On JDK 22+ (the JDK 25 runtime here), call C's strlen and getpid through Linker. Allocate a MemorySegment in an Arena, write a string, and pass it. Then show that accessing the segment after the arena closes throws, and that out-of-bounds access throws. Note the --enable-native-access warning.

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

C1. Modernise a Java 8 module of TiffinBox

Take an old-style module that has: - anonymous classes; - instanceof chains; - mutable beans with getters and setters; - Date; - StringBuffer; - raw collections; - finalize; - a platform-charset FileReader.

Modernise it step by step, with characterisation tests guarding behaviour: - records and sealed types; - pattern matching; - java.time; - streams where clearer; - try-with-resources; - explicit UTF-8; - virtual threads for its I/O fan-out.

Use OpenRewrite where possible and hand edits elsewhere. Report the line count, the bugs found during the modernisation, and the test results.

Combines: Volume 1's refactoring discipline, ch33–ch38's language features, and this chapter's upgrade tooling.

C2. A JDK upgrade pipeline

Set up CI for the TiffinBox service that: - builds and tests on the current LTS (21) and the next one (25); - runs jdeprscan and jdeps and fails on new forRemoval uses; - compares startup time (with and without an AOT cache) and memory (with and without compact headers) between the JDKs; - publishes a report artifact (the GC log summary, the startup numbers); - includes an early-access job allowed to fail.

Write the upgrade runbook that uses it.

Combines: Volume 2's CI and deployment (ch30, ch31), ch38's load considerations, and this chapter.

C3. Modern Java versus Kotlin for the same feature

Implement the payments module (sealed payments, fees, refunds, validation with errors collected) in modern Java 21/25 and in Kotlin. Compare: - null safety; - data classes against records; - when against switch patterns; - extension functions; - coroutines against virtual threads; - interop pain points (platform types, getFirst clashes from T5).

Decide whether TiffinBox should allow Kotlin modules.

Combines: ch33's language comparison and S3, ch34–ch38's features, and this chapter.

What the chapter leaves out

Release notes beyond JEPs

Many behaviour changes never get a JEP: TLS defaults, certificate root updates, Locale and CLDR data, time-zone database updates (tzdata, which matters for Asia/Kolkata rarely but for others often), JIT and GC defaults, and the removal of obsolete flags (which can stop the JVM from starting). Read the per-release release notes ("Removed Features and Options", "Known Issues"), not just the JEP list, before upgrading.

Multi-release JARs and supporting several JDKs in libraries

A library supporting JDK 17 and 21 can ship a multi-release JAR (META-INF/versions/21/…) containing versions of classes that use newer APIs (virtual threads, sequenced collections), compiled with --release for each. Spring, Jackson and Netty use this. Application teams rarely need it, but should recognise it when debugging which class actually loaded.

Vector API and Valhalla status

The Vector API (SIMD) has incubated since JDK 16, waiting for Valhalla's value classes before it's finalised. It gives large speedups for numeric kernels (similarity search, image processing). Valhalla (value classes, null-restricted types, specialised generics) is the biggest pending change to the language and VM, and it will change ch33–ch36's cost models. Track the JEPs; don't design around them yet.

Leyden beyond AOT caching

Project Leyden's goal is shifting computation from run time to earlier phases ("condensers"): AOT method profiling (JEP 515, 25), and future AOT code compilation. It aims to close part of the startup gap with native-image while keeping the open-world JVM. That matters for scale-to-zero and fast autoscaling (ch42). Expect more JEPs in 26–27.

Ecosystem baselines

Frameworks set the pace of your upgrades as much as the JDK does: - Spring Boot 3 requires JDK 17+, and Boot 4 is built on Spring Framework 7 with a JDK 17 baseline and JDK 25 support; - Jakarta EE 11 needs JDK 17+; - Hibernate 7, Kotlin and Gradle publish JDK compatibility matrices (Gradle needs a version that understands your JDK's class files to run on it).

Check the matrix of every key dependency before choosing a JDK.

Senior exercises

S1. Write the team's modern Java style guide

Write one page on which modern features to use by default: - records, sealed types, pattern switches, var rules; - text blocks for SQL and fixtures (bind parameters only); - sequenced methods; - java.time; - virtual threads; - Stream.toList.

Also say which features to avoid (previews in production, Optional fields), how the JDK version is chosen, and how adoption is enforced. Tie each rule to an output from this chapter.

S2. Review a "modernisation" pull request

A PR adds: - --enable-preview to the production build to use string templates (on JDK 21); - converts every entity (JPA @Entity classes) to records; - replaces Optional returns with var everywhere; - adds --add-opens java.base/java.lang=ALL-UNNAMED "to fix a test"; - switches the production GC to ZGC with -XX:+ZGenerational "for speed".

Write the review.

S3. Decide the JDK upgrade path for a fleet of services

TiffinBox runs 14 services: 9 on JDK 17 (Spring Boot 3.1), 3 on JDK 11 (Boot 2.7, end of life), and 2 on JDK 21. Plan the next 12 months: the target version, the order, the risks (Boot 2 → 3 means the javax → jakarta change), and how you'll measure success.

S4. Teach "what changed since Java 8" in 30 minutes

Prepare a talk for engineers returning to Java after years of Java 8. Use five live outputs: - P1's pattern switch; - the lab's exhaustiveness error; - P3's sequenced view; - the lab's virtual threads (5,289 ms against 158 ms, ch38); - P5's Security Manager failure on 25.

Structure it as "what to use, what to stop using, how upgrades work".

S5. Write the decision record for adopting JDK 25 features in the platform

Write an architecture decision record (ADR) for the platform team covering these JDK 25 features: - the AOT cache; - compact object headers; - generational ZGC for latency-sensitive services; - scoped values in the internal request-context library; - flexible constructor bodies and compact source files for ops scripts.

For each, give the decision (adopt, trial or hold), the evidence required, the rollout and the rollback.