The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·39

Modern Java Through JDK 27

How Java evolved from Java 8 to JDK 27, and why. Covers the six-month cadence and LTS choices, var, switch expressions, text blocks, records, sealed types, pattern matching and record patterns, virtual threads, scoped values, structured concurrency, the FFM API, sequenced collections, compact source files, the module system, the fate of string templates, preview-feature discipline, and runtime, GC, deprecation and removal changes. Each feature is traced to the languages it came from, and Java's evolution process is compared with those of C#, Kotlin, Go, Rust, C++, Python and Zig.

37 topics · ~36 min read · 32-question quiz
Updated Suggest a correction

Start here: the same program, ten years apart

Java keeps changing

Java 8 (2014) is still what many tutorials, Stack Overflow answers and older codebases show. Since 2017 a new Java version has shipped every six months (March and September), and every two years one of them is a long-term support (LTS) release that vendors patch for years: 8, 11, 17, 21, 25, with 29 due in September 2027. As of October 2026 the newest release is JDK 27 and the newest LTS is JDK 25. Each release adds a few features; new language features usually arrive as previews first (switched on with --enable-preview) and become final once the design settles. This chapter traces what changed and why; the quickest way to feel the difference is to read the same program written both ways.

Java 8 style

Java
static final class Order {
    private final int id; private final String status; private final long totalPaise;
    Order(int id, String status, long totalPaise) { … }
    int getId() { return id; } String getStatus() { return status; } long getTotalPaise() { return totalPaise; }
    @Override public boolean equals(Object o) { … 6 lines … }
    @Override public int hashCode() { return Objects.hash(id, status, totalPaise); }
    @Override public String toString() { return "Order[id=" + id + … + "]"; }
}
static String describe(Object event) {
    if (event instanceof Order) {
        Order o = (Order) event;
        if (o.getStatus().equals("PAID")) return "paid order " + o.getId();
        else if (o.getStatus().equals("NEW")) return "new order " + o.getId();
        else return "order " + o.getId() + " is " + o.getStatus();
    } else if (event instanceof String) return "message: " + event;
    return "unknown";
}
Map<String, List<Order>> byStatus = new HashMap<String, List<Order>>();
for (Order o : orders) {
    List<Order> list = byStatus.get(o.getStatus());
    if (list == null) { list = new ArrayList<Order>(); byStatus.put(o.getStatus(), list); }
    list.add(o);
}
String json = "{\n" + "  \"id\": " + last.getId() + ",\n" + "  \"status\": \"" + last.getStatus() + "\"\n" + "}";

Java 21 style

Java
enum Status { NEW, PAID, CANCELLED }
record Order(int id, Status status, long totalPaise) {}
sealed interface Event permits OrderEvent, Message {}
record OrderEvent(Order order) implements Event {}
record Message(String text) implements Event {}

static String describe(Event event) {
    return switch (event) {
        case OrderEvent(Order(var id, var status, var total)) when status == Status.PAID -> "paid order " + id;
        case OrderEvent(Order(var id, var status, var total)) when status == Status.NEW -> "new order " + id;
        case OrderEvent(Order o) -> "order " + o.id() + " is " + o.status();
        case Message(var text) -> "message: " + text;
    };
}
var byStatus = orders.stream().collect(groupingBy(Order::status, TreeMap::new, toList()));
var last = orders.getLast();
var json = """
    {
      "id": %d,
      "status": "%s"
    }""".formatted(last.id(), last.status());

Both print exactly the same thing:

Text
new order 1 | paid order 2 | message: hello
[NEW, PAID] | last: Order[id=2, status=PAID, totalPaise=4500]
{
  "id": 2,
  "status": "PAID"
}

What changed, feature by feature

Java 8 Modern Java Arrived
Class with fields, constructor, getters, equals, hashCode, toString record JDK 16
String constants for states enum (always existed, now used with exhaustive switch) Java 5 / JDK 21
instanceof then cast Pattern matching instanceof Order o JDK 16
if/else chains on types switch with type patterns, record patterns and when guards JDK 21
Object parameter for "one of several kinds" sealed interface: the compiler knows every case JDK 17
Repeating long generic types var for local variables JDK 10
Get-or-create loops for maps Streams and collectors (groupingBy), computeIfAbsent Java 8
list.get(list.size() - 1) getLast() on sequenced collections JDK 21
Escaped \n and \" in strings Text blocks """…""" with formatted JDK 15
Thread pools sized for blocking I/O Virtual threads JDK 21
public static void main(String[] args) in a class void main() in a compact source file JDK 25

The modern version is shorter (33 lines against 42 for the whole file), but the real gain is safety. The record can't have a stale hashCode; the enum can't hold "PIAD"; and because Event is sealed, the switch has no "unknown" fallback. Add a Refund event and the compiler refuses to build until describe handles it (lab experiment 3), where the Java 8 version would silently return "unknown" in production.

Upgrading safely

New syntax needs a newer compiler, and new library methods need a newer runtime. Two settings matter: --release N (compile against version N's language and API, so using List.of with --release 8 is an error) and the runtime version you deploy. A class compiled for a newer Java won't load on an older one (UnsupportedClassVersionError); a class compiled for an older Java runs on newer ones, which is why upgrading the runtime first is usually the safe order. The lab shows both, plus what JDK 25 gives an unchanged program: smaller objects and faster startup.

How deep to go in modern Java

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 Read modern Java: records, var, text blocks, switch expressions, patterns
L2 Write idiomatic JDK 21+ code with sealed types, pattern matching, sequenced collections and virtual threads
L3 Explain how features evolve (JEPs, previews, incubators), why string templates were withdrawn, and what the runtime gained (GCs, startup, headers)
L4 Diagnose version problems: --release mismatches, class file versions, removed APIs, preview flags, pinning on older JDKs
L5 Plan and run an LTS upgrade across services, with jdeps, tests and staged rollout
L6 Set a version policy (LTS cadence, vendor choice, adoption of new features) for an organisation

How Java evolves

The release train

Since JDK 9 (2017), Java has shipped a feature release every six months, in March and September. Features land when ready instead of holding up a release. Every two years (since 2021) one release is designated LTS (Long-Term Support) by vendors:

LTS Released Headline features since the previous LTS
8 2014 Lambdas, streams, java.time, default methods
11 2018 var (10), HTTP Client, single-file launch, JPMS (9), jshell (9)
17 2021 Records, sealed classes, text blocks, switch expressions, instanceof patterns, strong encapsulation of JDK internals
21 2023 Virtual threads, record patterns, pattern-matching switch, sequenced collections, generational ZGC
25 Sept 2025 Scoped values, compact source files and instance main, module imports, flexible constructor bodies, stream gatherers (24), FFM (22), unnamed variables (22), compact object headers, AOT cache improvements, JEP 491 (no pinning in synchronized, 24)
29 (expected) Sept 2027 —

Releases between LTS versions are fully production-quality, but each one is only patched until the next release six months later. As of late 2026, JDK 27 (September 2026) is the current release and JDK 25 the current LTS. Most enterprises deploy LTS versions. Teams with good test automation can track every release to get performance and GC improvements sooner.

"LTS" is a vendor commitment, not an OpenJDK one. Oracle, Eclipse Adoptium (Temurin), Amazon Corretto, Azul Zulu, Microsoft, Red Hat, BellSoft Liberica, IBM Semeru and SAP Machine each build OpenJDK and promise updates for their own durations. Spring Boot 4 requires Java 17 as a baseline and recommends 25.

The JEP process and preview features

Changes are proposed as JEPs (JDK Enhancement Proposals). Large language and API features go through stages:

  • Incubator modules (jdk.incubator.*): APIs still being designed, such as the Vector API, which is in its 12th incubation in JDK 27 because it's waiting on Valhalla's value classes.
  • Preview features: language or API features that are fully specified and implemented but not yet permanent. They change or disappear based on feedback, and each preview round gets a new JEP number.
  • Final (standard) features: permanent, covered by Java's strong compatibility promise.

Preview-feature discipline:

Terminal
$ javac --release 27 --enable-preview Main.java      # must name the exact release
$ java --enable-preview Main
# Class files compiled with preview features are marked; they won't run on a different JDK version.
  • Preview APIs can change incompatibly between releases. Structured concurrency's API was redesigned between the JDK 24 and JDK 25 previews (subclass-based ShutdownOnFailure became StructuredTaskScope.open() with Joiners).
  • Previews can be withdrawn entirely: string templates were previewed in JDK 21 and 22, then removed in JDK 23 (below).
  • Libraries shouldn't ship preview features to users, and production services should adopt them only with a plan to update every six months.
  • Use them in experiments, internal tools and test code to give feedback. That's what they're for.

How other languages evolve

Language Cadence Compatibility model Experimental features
Java 6 months Very strong backward compatibility; deprecation → forRemoval → removal over years Preview and incubator, opt-in per release
C#/.NET Yearly (November); even releases are LTS (.NET 8, .NET 10) Strong; nullable reference types were opt-in [RequiresPreviewFeatures], LangVersion=preview
Kotlin Language releases about every 6 months (2.x with the K2 compiler) Strong, with deprecation cycles @OptIn, -X flags, experimental annotations
Go 6 months (February and August) Go 1 compatibility promise (2012): code written for Go 1.0 still compiles. go.mod's go line and GODEBUG settings control behaviour changes, such as the 1.22 loop-variable change GOEXPERIMENT=…
Rust 6 weeks Stability guarantee for stable Rust. Editions (2015, 2018, 2021, 2024) allow opt-in syntax changes per crate, while crates of different editions link together Nightly-only #![feature(...)] gates
C++ ISO standard every 3 years (C++11, 14, 17, 20, 23, 26) Very strong ABI and source compatibility (sometimes to its detriment) Compiler-specific flags and technical specifications
Python Yearly (October), PEP-driven Mostly compatible since 3.0. Deprecations over 2+ releases from __future__ import …, provisional modules
Zig Irregular (0.x releases) Pre-1.0: breaking changes every release (std APIs, async removal, ArrayList unmanaged by default) Everything is in flux until 1.0

The theme across mature languages: fast, predictable cadence + strong compatibility + an explicit experimentation channel. Java's previews, Rust's nightly gates and C#'s preview flags are the same idea.

Language features, oldest to newest

var: local variable type inference (JDK 10)

Java
var orders = new ArrayList<Order>();                    // inferred ArrayList<Order>
var byCustomer = orders.stream().collect(Collectors.groupingBy(Order::customer));  // avoids a long type
for (var entry : byCustomer.entrySet()) { … }
try (var in = Files.newBufferedReader(p)) { … }
(var a, var b) -> a + b                                 // in lambda parameters (JDK 11), to allow annotations

// Not allowed: fields, method parameters, return types, var x; (no initialiser), var x = null;
// Pitfalls:
var list = new ArrayList<>();          // ArrayList<Object>: diamond plus var infers Object
var n = 1;                             // int; later n = 2L won't compile

var isn't a dynamic type: it's still static typing, with the type inferred from the initialiser. Use it when the type is obvious from the right-hand side or is noise. Avoid it when the inferred type isn't apparent (var result = service.process(x);). The ancestors are C# var (2007), C++11 auto, Scala/Kotlin val, Go :=, Rust let and ML-family Hindley–Milner inference.

Interactive diagram: Sealed types: the compiler knows every case. It needs JavaScript; the text around it says the same.

Switch expressions (JDK 14)

The old switch statement had fall-through (forget a break and execution continues into the next case), was statement-only, and didn't check exhaustiveness. Switch expressions fix all three:

Java
// Old
String label;
switch (day) {
    case SATURDAY: case SUNDAY: label = "weekend"; break;
    default: label = "weekday";
}

// New: arrow labels (no fall-through), multiple constants per case, an expression with a value
String label = switch (day) {
    case SATURDAY, SUNDAY -> "weekend";
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "weekday";   // exhaustive over the enum: no default needed
};
int bonus = switch (level) {
    case JUNIOR -> 1;
    case SENIOR -> {
        audit(level);
        yield 3;                                        // 'yield' returns a value from a block
    }
    default -> 2;
};

Without a default, an exhaustive enum switch expression compiles to code that throws MatchException (IncompatibleClassChangeError before JDK 21) if a new enum constant appears at run time from a separately compiled class. That's a safety net, not silence.

Text blocks (JDK 15)

Multi-line string literals with smart indentation stripping:

Java
String sql = """
    SELECT o.id, o.total
      FROM orders o
     WHERE o.customer_id = ?
       AND o.status = 'PAID'
    ORDER BY o.created_at DESC
    """;                                   // the closing delimiter's position sets the common indent to strip

String json = """
    {"id": %d, "name": "%s"}\
    """.formatted(id, name);               // \ at end of line: no newline; \s: a significant trailing space

Incidental whitespace (the common leading indent) is stripped, line endings are normalised to \n, and trailing spaces are removed unless escaped. Ancestors: Python """, Kotlin raw strings with trimIndent(), C# raw string literals (""", C# 11), Rust raw strings r#"..."#, and Go backtick strings (no escapes, no indent stripping). Zig has \\ line-prefixed multiline strings.

Records (JDK 16)

Covered in chapter 33: transparent, shallowly immutable data carriers with generated constructor, accessors, equals, hashCode and toString. Details worth knowing for modern Java:

Java
public record Range(int lo, int hi) {
    public Range {                                  // compact canonical constructor
        if (lo > hi) throw new IllegalArgumentException("lo > hi");
    }
    public Range(int point) { this(point, point); } // additional constructors must delegate to the canonical one
    public int length() { return hi - lo; }         // methods are fine
    static Range EMPTY = new Range(0, 0);           // static fields OK; instance fields beyond components are not
}
// Records can implement interfaces, be generic, be nested (implicitly static), and be declared locally inside methods.
// Serialisation uses the canonical constructor (validation runs during deserialisation, unlike ordinary classes).
// Jackson 2.12+, Spring's data binding, JPA projections and Hibernate's embeddables support records.
// JPA ENTITIES can't be records (entities need mutability, a no-arg constructor and proxies).

Sealed classes and interfaces (JDK 17)

A sealed type restricts which classes may extend or implement it. That gives a closed hierarchy: the sum types of chapter 33, in Java.

Java
public sealed interface PaymentResult
        permits Approved, Declined, RequiresAction {}                      // the complete list of subtypes

public record Approved(String authCode, Money amount) implements PaymentResult {}
public record Declined(String reason, boolean retryable) implements PaymentResult {}
public non-sealed class RequiresAction implements PaymentResult {          // re-opens this branch for extension
    public final URI redirect;
    public RequiresAction(URI redirect) { this.redirect = redirect; }
}
// Each permitted subclass must be final, sealed, or non-sealed. Records are implicitly final.
// Permitted subclasses must be in the same module (or the same package, in the unnamed module).

Why this matters: the compiler now knows all the cases, so a switch over a sealed type can be exhaustive with no default. Adding a new permitted subtype then breaks compilation everywhere it isn't handled, which is exactly what you want for domain states, commands, events, API results and AST nodes. Ancestors: ML/Haskell ADTs, Scala sealed trait, Kotlin sealed class, Rust enum, Swift enum with payloads, and TypeScript discriminated unions.

Pattern matching

Pattern matching arrived in steps:

Java
// 1. instanceof patterns (JDK 16): test + cast + bind in one step
if (obj instanceof String s && !s.isBlank()) {     // s in scope where the match is known to have succeeded
    use(s.strip());
}
if (!(obj instanceof Order o)) return;              // flow scoping: o is in scope after this line
process(o);

// 2. Pattern-matching switch (JDK 21): switch on types, with guards and null handling
String describe(PaymentResult r) {
    return switch (r) {
        case Approved a when a.amount().isZero() -> "zero-amount approval";   // guard: 'when'
        case Approved a                          -> "approved " + a.authCode();
        case Declined d when d.retryable()       -> "declined, retry later";
        case Declined d                          -> "declined: " + d.reason();
        case RequiresAction ra                   -> "redirect to " + ra.redirect;
    };                                                                         // exhaustive: no default
}
// More specific cases must come first (dominance is checked).
// 'case null' is allowed; without it, a null selector throws NullPointerException as before.

// 3. Record patterns (JDK 21): deconstruct records, nested
record Point(int x, int y) {}
record Line(Point from, Point to) {}

static int manhattan(Object o) {
    return switch (o) {
        case Line(Point(var x1, var y1), Point(var x2, var y2)) -> Math.abs(x2 - x1) + Math.abs(y2 - y1);
        case Point(int x, int y) -> Math.abs(x) + Math.abs(y);
        default -> 0;
    };
}

// 4. Unnamed variables and patterns (JDK 22): '_' for things you don't use
case Declined(_, var retryable) -> …
try { … } catch (NumberFormatException _) { … }
for (var _ : items) count++;
map.forEach((_, v) -> total += v);

// 5. Primitive types in patterns, instanceof and switch: PREVIEW (fifth preview in JDK 27)
// switch (code) { case int i when i >= 500 -> …; case 404 -> …; }   (preview)

Data-oriented programming is the style these features enable (Brian Goetz's term). Model data as records (immutable), model alternatives as sealed interfaces, and write behaviour as functions that pattern-match over them, instead of spreading visit methods across a class hierarchy. It answers the expression problem (chapter 34) by choosing the "easy new operations" side, with the compiler checking exhaustiveness.

Java
// A small interpreter: the classic showcase
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(double v) implements Expr {}
record Add(Expr l, Expr r) implements Expr {}
record Mul(Expr l, Expr r) implements Expr {}
record Neg(Expr e) implements Expr {}

static double eval(Expr e) {
    return switch (e) {
        case Num(var v) -> v;
        case Add(var l, var r) -> eval(l) + eval(r);
        case Mul(var l, var r) -> eval(l) * eval(r);
        case Neg(var x) -> -eval(x);
    };
}
static Expr simplify(Expr e) {
    return switch (e) {
        case Mul(Num(var v), var x) when v == 1 -> simplify(x);
        case Mul(Num(var v), _) when v == 0 -> new Num(0);
        case Neg(Neg(var x)) -> simplify(x);
        default -> e;
    };
}

The same program in languages that had these features first:

enum Expr { Num(f64), Add(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), Neg(Box<Expr>) }

fn eval(e: &Expr) -> f64 {
    match e {
        Expr::Num(v) => *v,
        Expr::Add(l, r) => eval(l) + eval(r),
        Expr::Mul(l, r) => eval(l) * eval(r),
        Expr::Neg(x) => -eval(x),
    }
}
// Box is needed because a recursive enum would otherwise have infinite size.

Flexible constructor bodies (JDK 25)

Before JDK 25, super(...) or this(...) had to be the first statement in a constructor, so validating or preparing arguments required static helper methods. JEP 513 allows statements before the explicit constructor call, as long as they don't use the instance under construction (except to assign its fields):

Java
public class PositiveBigInteger extends BigInteger {
    public PositiveBigInteger(long value) {
        if (value <= 0) throw new IllegalArgumentException("non-positive: " + value);  // fail fast, before super
        super(Long.toString(value));
    }
}

Compact source files and instance main (JDK 25)

JEP 512 finalised a gentler on-ramp: a source file can contain top-level methods and fields with no class declaration, and main can be an instance method with no String[] parameter. The new java.lang.IO class provides IO.println and IO.readln. Together with launching multi-file source programs (java Main.java, JEP 458, JDK 22), small tools and scripts no longer need a build setup.

Java
// Hello.java: run with  java Hello.java
void main() {
    String name = IO.readln("Name? ");
    IO.println("Hello, " + name);
}

Module import declarations (JEP 511, JDK 25) import all exported packages of a module in one line: import module java.base;. Compact source files import java.base automatically.

What happened to string templates

String templates (STR."Hello \{name}") were previewed in JDK 21 and 22, then withdrawn in JDK 23. The design (template processors that could validate and safely render SQL, JSON or HTML, not merely concatenate) generated feedback that the processor model and syntax weren't right. They're being redesigned, with no committed release as of JDK 27. Meanwhile:

Java
String msg = "Order %s for %s".formatted(id, customer);            // String.formatted (JDK 15)
String msg2 = MessageFormat.format("Order {0} for {1}", id, customer);
// For SQL: never concatenate or format user input. Use bind parameters (JdbcClient, jOOQ, JPA) (chapter 49).

That safety concern was the key motivation. String interpolation in other languages (f"…" in Python, $"…" in C#, "${x}" in Kotlin, format! in Rust, template literals in JS) makes injection easy when developers interpolate into SQL or HTML. JavaScript's tagged templates and C#'s interpolated string handlers are closer to what Java was aiming for: templates that a processing function can validate.

Libraries and APIs

Sequenced collections (JDK 21)

Before JDK 21, there was no common type for "a collection with a defined order", and getting the last element was inconsistent: list.get(list.size() - 1), deque.getLast(), sortedSet.last(), or iterating a LinkedHashSet to the end. JEP 431 added three interfaces into the existing hierarchy:

Java
interface SequencedCollection<E> extends Collection<E> {
    SequencedCollection<E> reversed();      // a reverse-ordered VIEW
    void addFirst(E e); void addLast(E e);
    E getFirst(); E getLast();
    E removeFirst(); E removeLast();
}
// SequencedSet<E>, and SequencedMap<K,V> with firstEntry(), lastEntry(), pollFirstEntry(), putFirst(), reversed(),
// sequencedKeySet(), sequencedValues(), sequencedEntrySet().

List<Order> recent = orders.reversed();                 // no copy
Order newest = orders.getLast();
var lhm = new LinkedHashMap<String, Integer>();
lhm.putFirst("urgent", 1);

List, Deque, LinkedHashSet, SortedSet, LinkedHashMap and SortedMap were retrofitted to implement them. Unmodifiable collections throw on the mutators, as usual.

Other API additions worth knowing

Version API
9 List.of/Set.of/Map.of, Optional.ifPresentOrElse/stream, Stream.takeWhile/dropWhile/iterate(seed, hasNext, next), ProcessHandle, VarHandle, reactive Flow interfaces
11 HttpClient (HTTP/2, async), String.isBlank/strip/lines/repeat, Files.readString/writeString, Predicate.not
12–16 Collectors.teeing, String.indent/transform, Stream.toList, Stream.mapMulti, the helpful NullPointerException messages (JEP 358: "Cannot invoke … because x.y is null")
17 RandomGenerator interfaces, HexFormat, deserialisation filters
19–21 HashMap.newHashMap(n), Math.clamp, StringBuilder.repeat, Character.isEmoji, String.indexOf(ch, from, to)
22 Foreign Function & Memory API (final), launching multi-file programs, Class-File API preview
23 Markdown documentation comments (///), ZGC generational by default
24 Stream Gatherers (final), Class-File API (final), ML-KEM and ML-DSA post-quantum algorithms, synchronized no longer pins virtual threads
25 Scoped values (final), module imports, compact source files, flexible constructor bodies, Key Derivation Function API, PEM encodings (preview), stable values (preview, renamed lazy constants in 26)
26 HTTP/3 for HttpClient, AOT object caching with any GC, "prepare to make final mean final" warnings, Applet API removed
27 Post-quantum hybrid key exchange for TLS 1.3, G1 the default collector in all environments, compact object headers on by default, JFR in-process data redaction, lazy constants (third preview), structured concurrency (seventh preview)

Foreign Function & Memory API (JDK 22)

FFM (Project Panama) replaces JNI for calling native code and managing off-heap memory. No C glue code or header compilation is needed, and access is bounds-checked and lifetime-checked with arenas:

Java
// Call C's strlen from Java
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
    linker.defaultLookup().find("strlen").orElseThrow(),
    FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));

try (Arena arena = Arena.ofConfined()) {                 // all memory allocated here is freed at close
    MemorySegment cStr = arena.allocateFrom("Hello, Panama");
    long len = (long) strlen.invokeExact(cStr);          // 13
}   // accessing cStr after this throws IllegalStateException: no use-after-free

// Off-heap structured memory with layouts (like C structs)
StructLayout POINT = MemoryLayout.structLayout(ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y"));
VarHandle X = POINT.varHandle(MemoryLayout.PathElement.groupElement("x"));
  • jextract generates Java bindings from C headers (as bindgen does for Rust and cgo for Go).
  • Restricted methods (those that can crash the JVM) print warnings unless enabled with --enable-native-access=ALL-UNNAMED (or per module), part of the "integrity by default" direction.
  • Use cases: calling native libraries (compression, ML runtimes, OS APIs), large off-heap buffers (> 2 GB, which ByteBuffer can't address), memory-mapped files, and zero-copy interop.

How other languages call C, the universal ABI:

Language Mechanism Cost and safety
Java FFM (JNI before) Downcalls are JIT-intrinsified and cheap; arenas give memory safety; native code itself is unchecked
C# P/Invoke ([LibraryImport] source-generated in .NET 7+), unsafe pointers, Span<T> Mature and cheap
Go cgo Each call costs tens of nanoseconds (stack switching, scheduler interaction); complicates cross-compilation; "cgo is not Go"
Rust extern "C" + unsafe blocks; bindgen Zero-cost: same ABI, no runtime
Zig @cImport of C headers directly; Zig is also a C/C++ compiler (zig cc) Zero-cost, the smoothest C interop of any language
C++ Native (extern "C") Zero-cost
Python ctypes, cffi, C extensions, pybind11, PyO3 (Rust) Per-call overhead; how NumPy and friends work

Concurrency features recap

Covered in chapter 38: virtual threads (21), synchronized without pinning (24), scoped values (25, final), structured concurrency (preview through 27). Together they're Java's answer to Go's goroutines and Kotlin's coroutines, chosen to avoid function colouring and keep existing blocking APIs (JDBC, InputStream) usable at scale.

The module system

JPMS in brief

The Java Platform Module System (Project Jigsaw, JDK 9) added a unit above packages. A module declares, in module-info.java, which modules it requires and which packages it exports:

Java
module com.shop.orders {
    requires com.shop.common;                  // reads that module
    requires transitive com.shop.money;        // and re-exports it to whoever requires orders
    requires static lombok;                    // compile-time only

    exports com.shop.orders.api;               // public types in this package are accessible outside
    exports com.shop.orders.spi to com.shop.plugins;   // qualified export
    opens com.shop.orders.model to com.fasterxml.jackson.databind, org.hibernate.orm.core;  // deep reflection allowed

    uses com.shop.orders.spi.PricingRule;      // ServiceLoader consumer
    provides com.shop.orders.spi.PricingRule with com.shop.orders.internal.DefaultRule;
}

What it achieved:

  • Strong encapsulation: public is no longer "public to everyone". Only exported packages are accessible, and deep reflection (setAccessible) into non-opened packages fails.
  • Reliable configuration: missing modules and split packages are detected at startup instead of failing as NoClassDefFoundError at run time.
  • A modularised JDK: jlink builds a custom runtime image containing only the modules you use (smaller containers).
  • JDK internals locked down: sun.misc.Unsafe and friends went from "accessible" (8) to warnings (9–15) to strongly encapsulated by default (16–17, JEP 403). --add-opens java.base/java.lang=ALL-UNNAMED is the escape hatch you see in older frameworks' instructions. sun.misc.Unsafe memory-access methods are being deprecated and removed in favour of VarHandle and FFM (JEP 471, 498).

The reality in application development: most Spring Boot applications run on the class path (the unnamed module) and don't write module-info.java. Frameworks rely heavily on reflection, and many libraries aren't modularised. JPMS matters most for the JDK itself, for libraries that want encapsulation, and for jlink-built runtimes. Chapter 42 covers class path versus module path in packaging detail.

Comparable systems: Go modules plus internal/ packages (simpler and much more widely adopted), Rust crates with pub(crate), C# assemblies with internal, C++20 modules (slow adoption, as build-system support arrived gradually), OSGi on the JVM (dynamic, complex), and Kotlin's internal modifier.

Runtime evolution

JVM, GC and performance changes

A JDK upgrade is often the cheapest performance improvement available. Selected runtime changes:

Area Changes
Garbage collectors (chapter 40) G1 the default since 9 (and in all environments since 27). ZGC production in 15, generational ZGC in 21 and default ZGC mode in 23, non-generational mode removed in 24. Shenandoah production in 15, generational Shenandoah product in 25. CMS removed in 14. Parallel and Serial remain
Object layout Compact object headers (JEP 450 experimental in 24, JEP 519 product in 25, default in 27): headers drop from 12 to 8 bytes, typically cutting heap use by 10–20% for object-heavy applications
Startup (Project Leyden) Class Data Sharing (CDS, archived app classes since 10/13), then the AOT cache: class loading and linking (JEP 483, JDK 24), simpler command-line ergonomics and method profiling (JEPs 514/515, JDK 25), object caching with any GC (JEP 516, JDK 26). Faster startup and warmup without GraalVM native-image's closed-world restrictions
Containers Container awareness (8u191/10+): the JVM reads cgroup CPU and memory limits. Use -XX:MaxRAMPercentage=75 instead of a fixed -Xmx in containers
Strings Compact strings (9), indified string concatenation (9), string deduplication in G1
Diagnostics JFR open-sourced (11), JFR streaming (14), helpful NPEs (14/15), JFR in-process redaction (27)
Security TLS 1.3 (11), post-quantum ML-KEM/ML-DSA (24), hybrid PQ key exchange in TLS (27), Security Manager permanently disabled (24)

Deprecations and removals

Java removes things slowly and loudly: @Deprecated(forRemoval = true), then warnings, then removal, usually across several releases. Notable removals that break old code:

Removed or disabled When Replacement
Java EE and CORBA modules (javax.xml.bind, javax.annotation, JAX-WS) 11 Jakarta EE artifacts (jakarta.* namespace)
Nashorn JavaScript engine 15 GraalJS
RMI Activation, Applet API (deprecated 9) 17, 26 —
Strong encapsulation of internals (--illegal-access removed) 17 Public APIs, --add-opens as a stopgap
Security Manager Deprecated 17, permanently disabled 24 (JEP 486) Container and process isolation, OS sandboxing
Finalization (finalize()) Deprecated for removal 18 (JEP 421) try-with-resources, Cleaner
32-bit x86 port Removed 25 64-bit
Thread.stop/suspend/resume stop throws UnsupportedOperationException since 20 Interruption
sun.misc.Unsafe memory access Warnings from 24, removal planned VarHandle, FFM
JNI/FFM unrestricted native access Warnings now, restrictions coming ("integrity by default") --enable-native-access
Final fields mutable via deep reflection Warnings from 26 (JEP 500, "prepare to make final mean final") Don't mutate finals (affects some serialisation and DI libraries)

The javax → jakarta move deserves a mention for Spring developers. When Oracle transferred Java EE to the Eclipse Foundation, the javax.* namespace couldn't move with it. Jakarta EE 9 renamed every package to jakarta.*. Spring Boot 3 / Spring Framework 6 (2022) moved to Jakarta EE 9+, so upgrading from Boot 2 means rewriting imports (javax.persistence → jakarta.persistence, javax.servlet → jakarta.servlet). OpenRewrite recipes automate it. Spring Boot 4 / Framework 7 (late 2025) moved to a Jakarta EE 11 baseline.

Tracking change as a working engineer

  • Read each release's JEP list (openjdk.org/projects/jdk/NN) and the release notes, which list removals and behaviour changes in detail.
  • Run tests on the early-access builds of the next release in CI (a non-blocking job) to catch breakage early.
  • Use jdeprscan (finds uses of deprecated APIs) and jdeps --jdk-internals (finds internal API use).
  • Automate migrations with OpenRewrite recipes (Java version upgrades, Spring Boot upgrades, JUnit 4 → 5) and with the IDE's inspections.
  • Track the projects that shape the future: Valhalla (value classes, JEP 401, being merged into the mainline for a release after 27, then null-restricted types and specialised generics), Leyden (startup and AOT), Panama (FFM, Vector API), Loom (structured concurrency), Babylon (code reflection for GPU and ML), and Amber (language productivity: patterns, records, string templates' successor).

The big picture

Java's evolution since 2014 shows a deliberate convergence with ideas from other languages, adapted to Java's compatibility constraints:

Idea Origin Java form
Lambdas, higher-order functions Lisp, ML, Haskell, Scala, C# Lambdas over functional interfaces (8)
Local type inference ML, C#, C++11, Scala var (10)
Data classes Scala case classes, Kotlin data classes, C# records Records (16)
Sum types ML, Haskell, Rust, Scala, Kotlin Sealed types (17)
Pattern matching ML (1970s), Haskell, Scala, Rust instanceof, switch and record patterns (16–21)
Lightweight threads Erlang (1986), Go (2009) Virtual threads (21)
Structured concurrency Trio (Python), Kotlin coroutines StructuredTaskScope (preview)
Scripting on-ramp Python, Go go run, Kotlin script Compact source files, java File.java (11–25)
Value types C# structs, C++, Rust, Swift Valhalla (in progress)
Safe native interop Rust FFI, Zig @cImport, C# P/Invoke FFM (22)

Java's distinctive constraint is that old code must keep running, often binary-compatible across decades. That's why features arrive later than in younger languages and why some (generic erasure, nullable-by-default references, checked exceptions) can't be undone. In exchange you get an ecosystem where a 2004 library usually still works on JDK 27.

Lab: versions, compatibility and what an upgrade buys

Compiled with JDK 21's javac; run on JDK 21 and on a JDK 25.0.2 runtime. Five experiments on the version mechanics that decide whether an upgrade is boring or an outage.

Experiment 1: --release versus -source/-target

Java
class R { public static void main(String[] a) { List<Integer> xs = List.of(1, 2); System.out.println(xs); } }
Text
$ javac --release 8 R.java
R.java:2: error: cannot find symbol
  symbol:   method of(int,int)
  location: interface List

$ javac -source 8 -target 8 R.java      → compiles without error

-source 8 -target 8 only restricts the language and the class file format; it still compiles against JDK 21's library, so List.of (added in JDK 9) slips through and fails with NoSuchMethodError the first time it runs on a real Java 8. --release 8 compiles against a recorded copy of Java 8's API signatures and catches it at build time. Always use --release (Maven's maven.compiler.release, Gradle's options.release or toolchains).

Experiment 2: class file versions

Text
$ javap -v R.class | grep major
  major version: 65                                  ← compiled for JDK 21

$ java -cp v25 R                                     ← the same class, version byte set to 69 (JDK 25), run on JDK 21
java.lang.UnsupportedClassVersionError: R has been compiled by a more recent version of the Java Runtime
(class file version 69.0), this version of the Java Runtime only recognizes class file versions up to 65.0

$ java25 -cp v25 R  → [1, 2]
$ java25 -cp v R    → [1, 2]                         ← a JDK 21 class runs unchanged on JDK 25

Every class file records the version it was compiled for (version = JDK + 44: 52 is Java 8, 61 is 17, 65 is 21, 69 is 25, 71 is 27). Runtimes load anything up to their own version, never newer. That asymmetry dictates upgrade order: upgrade the runtime first (old classes keep working), then raise --release once everything runs on the new runtime. A library that raises its own release (Spring Framework 7 and Hibernate 7 need JDK 17+, for example) forces your runtime up, which is how most teams discover the error above.

Experiment 3: sealed types make additions safe

Adding a third event type to the Java 21 program from Start here, without touching describe:

Java
sealed interface Event permits OrderEvent, Message, Refund {}
record Refund(int orderId) implements Event {}
Text
New.java:14: error: the switch expression does not cover all possible input values
        return switch (event) {

The compiler lists every switch that now needs a case, across the whole codebase. The Java 8 version, with its instanceof chain and return "unknown", compiles fine and mishandles refunds at run time. Note what this costs too: adding a permitted subtype to a sealed type in a published library is a breaking change for every client with an exhaustive switch, so seal types you own end to end (domain events, results) and keep open interfaces for extension points.

Experiment 4: compact object headers

Five million instances of record Point(int x, int y), measured as heap growth after GC:

Text
JDK 21:                               24.0 bytes per Point
JDK 25:                               24.0 bytes per Point
JDK 25 -XX:+UseCompactObjectHeaders:  16.0 bytes per Point

A Point's data is 8 bytes; the rest is the object header (12 bytes: mark word plus compressed class pointer) rounded up to an 8-byte boundary. Project Lilliput's compact headers (JEP 519, a product option in JDK 25, on by default in JDK 27) squeeze the header into 8 bytes, so this object shrinks by a third with no code change. Services that hold many small objects (caches, collections of records, ORM entities) see less memory, fewer GCs and better cache use; the full-depth section on runtime evolution and chapter 41 explain the layout.

Experiment 5: startup with the AOT cache

A small program that touches the HTTP client, streams, collections, java.time and virtual threads (about 2,000 classes loaded), best of seven runs:

Text
JDK 21: 622 ms | JDK 25: 585 ms | JDK 25 with AOT cache: 498 ms
(hello world: JDK 21 43 ms, JDK 21 with class data sharing off 80 ms)

Most of a Java program's startup is loading, verifying and linking classes. Class Data Sharing has archived the JDK's own classes for years (turning it off nearly doubles hello world's time). JDK 24 and 25 (Project Leyden, JEPs 483 and 514) extend that to your application: one training run with -XX:AOTCacheOutput=app.aot records the loaded and linked classes (a 19 MB file here), and later runs start from it, about 15% faster for this tiny program. Large frameworks gain more because they load tens of thousands of classes: Spring Boot applications have reported startup reductions of 40% or more. The cache requires the same JDK and classpath (it refused a directory classpath, so the program was packaged as a JAR). GraalVM native-image goes further, to tens of milliseconds, at the price of a closed-world build (chapter 42).

Try it yourself

  1. Run jdeps --jdk-internals your-app.jar on an old application and list the internal APIs it uses that a newer JDK encapsulates.
  2. Compile experiment 1 with --release 11 and --release 17. Which errors and warnings change?
  3. Measure experiment 4 with record Point(long x, long y) and with a class holding one byte. Where does compact headers help most?
  4. Use -Xlog:class+load with and without the AOT cache and count how many classes come from the "shared objects file".

Revision sheet: modern Java

Key ideas

  • Cadence: a release every March and September; LTS every two years (8, 11, 17, 21, 25; next 29); features go through JEPs, previews (--enable-preview) and incubator modules before becoming final.
  • Language, by release: lambdas and streams (8); var (10); switch expressions (14); text blocks (15); records and pattern instanceof (16); sealed types (17); pattern switch and record patterns (21); unnamed variables _ (22); flexible constructor bodies, module imports, compact source files with instance main (25); primitive patterns in preview.
  • Libraries: HttpClient (11), sequenced collections (21), virtual threads (21), FFM API for native code (22), stream gatherers (24), scoped values (25), structured concurrency (preview), class-file API (24).
  • Withdrawn: string templates (previewed in 21–22, withdrawn in 23, redesign pending).
  • Runtime: G1 default, ZGC generational-only, Shenandoah generational; compact object headers (product in 25, default in 27); Leyden AOT cache (24+); Unsafe memory access deprecation; Security Manager permanently disabled (24); 32-bit x86 port removed.
  • Compatibility: --release; class file version = JDK + 44; upgrade runtime first; jdeps for internal-API use; strong encapsulation of JDK internals since 17.
  • Comparisons: C# (yearly, aggressive language evolution), Kotlin (features first, Java later), Go (1.x compatibility promise, generics in 1.18), Rust (editions), C++ (three-year standards), Python (yearly, deprecation cycles).

Numbers to remember

  • Class file versions: 52 = 8, 55 = 11, 61 = 17, 65 = 21, 69 = 25, 71 = 27.
  • Lab: a two-int record took 24 bytes, 16 with compact headers; AOT cache cut a small app's startup about 15%.

Pitfalls

  • -source/-target without --release (runtime NoSuchMethodError on old JDKs).
  • Deploying classes compiled for a newer JDK than the runtime.
  • Preview features in production code; relying on sun.misc.Unsafe or reflective access to JDK internals.
  • Sealing published library types that clients switch over (adding a subtype breaks them).
  • Upgrading compile target and runtime in one step across many services.

Glossary

  • JEP: JDK Enhancement Proposal.
  • LTS: long-term support release.
  • Preview feature: complete but not final; may change or be removed.
  • Record pattern: a pattern that deconstructs a record into its components.
  • AOT cache: an archive of loaded and linked classes (and profiles) produced by a training run.
  • Compact object headers: 8-byte object headers (Project Lilliput).