The Modern Java Subset: What to Retire, What to Write Instead

engineering
languages
java
Records, sealed types, and pattern matching replace much of the boilerplate vocabulary of Java 8. Twenty-five numbered rules, what to write instead, and the six cases the subset does not cover.
Published

November 5, 2026

Java now contains two languages. One is the Java most codebases were built with, for reasons: mutable beans because serialization and the frameworks demanded them, checked exceptions because Java made failure part of the signature, synchronized because it was the lock the language gave, and class hierarchies because they were the reuse mechanism before generics. The other arrived between Java 16 and Java 25. It covers the same ground in less code, and it leaves less for you to reconstruct.

This page is the substitution table. It names the construct to retire, the construct that supersedes it, and the reason the replacement is better. It also names where the replacement stops, because a guideline that claims full coverage leaves you to find the gaps in production.

The subset narrows what you write. The platform keeps every old construct, so nothing here changes what Java costs — only what your code does with it.

The three substitutions that carry most of the value:

Some rows name a mechanism code such as T10 or C5. Those codes come from a 99-entry inventory that prices what a language forces on the code, using the analysis’s authored weights rather than measurements. Each code links to its entry in the criteria catalogue.

Target: Java 25. It is the current long-term-support release. Platform claims below cite the JDK 25 specification, the JDK 25 API documentation, or the Java Enhancement Proposal that decides it; claims about libraries and build tools are cited in place. Java 26 and Java 27 finalise no language feature: both spend their releases on the runtime, and the Java 26 and Java 27 pages record why. Two constructs useful to this subset are still previews in Java 27 (primitive types in patterns, and StructuredTaskScope), so using them needs --enable-preview and produces class files that will not load on a stock runtime [1], [2].

Which rows apply to you. At Java 21 every row applies except item 22, which needs 25. At Java 17, items 2, 9, 10, 11 and 21 wait for 21, item 24 waits for 19, and item 3 applies for sealing alone — its exhaustive switch needs 21. Records, sealed types, and the rest apply, except item 22. A published library must compile to its oldest consumer’s --release, so it can adopt only the rows that floor allows. Android has no virtual threads and no scoped values.

1 What changed, and when

Release Construct What it replaced
8 lambdas, streams, Optional, java.time anonymous classes, loop-built collections, null conventions, Date
9 List.of, Map.of [3], Cleaner, the module system (module-info.java) Collections.unmodifiableList, finalize(), classpath sprawl
16 records [4], pattern matching for instanceof [5] the bean: fields, getters, setters, equals, hashCode, toString
17 sealed types [6] the Visitor pattern for a closed set of cases
21 record patterns [7], switch patterns [8], virtual threads [9], sequenced collections (getFirst, getLast, reversed) [10] casts after instanceof, the visitor dispatch, thread-per-request pools, get(0)/get(size()-1)
22 Foreign Function and Memory API [11] JNI and Unsafe at the native boundary
25 scoped values [12], module imports (import module M;) [13], compact source files (one file, no class declaration) [14] ThreadLocal for most uses, import lists, one-class-per-file for small programs

Three constructs do most of the work in this list: records, sealed types, and pattern matching. Records supply the data, sealed types close the set of cases, and a pattern switch makes the compiler check that every case is handled. None of the three does it alone.

The module system is on this list as a release fact, not as a recommendation. Most libraries are still automatic modules, and the --add-exports flags in the enforcement section are classpath-build flags, not module declarations.

2 Data shape

Retire Write instead Why Since · mechanism
class with fields, getters, setters, equals, hashCode, toString record The data and its accessors are declared once, and there is no setter — though a mutable component is still a shared write path. If the codebase uses Lombok for this, records take the immutable value classes and Lombok keeps builders, mutable framework beans, and logging. 16
C2 C6 C8
class hierarchy plus a Visitor sealed interface plus record cases plus switch The compiler checks that every case is handled, and a new case breaks every exhaustive switch that does not handle it. Keep the Visitor where an operation has to be added from outside the module that owns the type. 17, exhaustive at 21
T4, removed at 21
instanceof, cast, then accessors record pattern The type test and the binding are one construct, so there is no separate cast to keep in step. 21
—
Object[], Map<String, Object>, parallel fields a record The shape gets a name, and a name can be checked. 16
—
null meaning “absent” Optional when the caller has a defined behaviour for “not there”; an empty collection for a collection The return type states that absence is possible. Optional is documented as a return type rather than a field type, and never null itself [15]. 8
T10
Optional.get() orElse, map, flatMap, or orElseThrow() where the absence is a bug get() and orElseThrow() throw the same NoSuchElementException; the difference is that the second makes the throw visible at the call site. orElse and map remove the throw entirely. 8, no-arg orElseThrow at 10
T10
double for money long minor units or BigDecimal Binary floating point cannot represent 0.10 exactly. long counts cents; BigDecimal carries a decimal scale and a rounding mode. 1.1
—
char, String.length(), substring by index codePointAt, codePoints(), offsetByCodePoints char is a UTF-16 code unit: a non-BMP emoji is two of them and a joined sequence is more [16]. Code points fix surrogate pairs; counting what a user calls a character needs BreakIterator or ICU4J. 1.5, codePoints() at 8
T15

A sealed interface declares, or lets the compiler infer, which types may implement it, and no other type can [6]. The subtypes live in the same module, or the same package in the unnamed module, so a hierarchy another module must extend is an open interface. Since Java 14 a switch can also be an expression that yields a value, and an arrow arm does not fall through [17]. Since Java 21 a case label can destructure a record: the pattern names the type and binds each field in declaration order [7].

sealed interface Shape permits Circle, Square, Rectangle {}

record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {
        case Circle(double r) -> Math.PI * r * r;
        case Square(double s) -> s * s;
        case Rectangle(double w, double h) -> w * h;
    };
}

Every case is listed, so the compiler proves the switch exhaustive: it checks that no case is missing [8]. Add Triangle to the permits clause and each exhaustive switch expression stops compiling on the next build of every module that compiles against it; a dependent that is never rebuilt throws MatchException at runtime instead. Adding a permitted case is a breaking change.

A default branch, or a catch-all case Shape s, absorbs the new case silently. That is one rule in this pattern the compiler cannot enforce for you.

Two limits matter. A record is shallowly immutable: it holds its components final, but an array component still shares the array and its equals/hashCode are identity-based, so record Span(int[] values) shares its buffer and two equal-value spans are two set elements. Copy the array in the compact constructor and in the accessor to stop the buffer being shared, and override equals and hashCode over the contents — the generated pair stays identity-based. Or hold the buffer in a plain class that copies on the way in and out [18]. And a sealed type is closed by design, which makes it wrong for extension points.

3 Errors

Retire Write instead Why Since · mechanism
throw new RuntimeException for a domain failure a Result<T, E> you define, returned from the method The domain failure is in the signature, and the interface carries no accessor, so reaching the value takes a pattern match. Unchecked exceptions still escape it, because the type cannot state them. 21
Er2
try/catch in the middle of a pipeline map, flatMap, fold on the result The failure travels through the expression instead of interrupting it. 21
Er4
throws on domain methods that cross a stream or a lambda the same result type at the domain boundary The JDK’s Stream and Function signatures cannot carry a checked exception, so each one needs a custom functional interface. A value composes with map and flatMap unchanged. Where the chain never enters a lambda, throws keeps the stack trace and is the better choice. 21
Er2 Er4
null or Optional used to report a failure the result type Absence is one fact: the caller has a defined behaviour for “not there”. Failure is another: the caller must react differently depending on why. 17, exhaustive dispatch at 21
Er4

Three kinds of failure look alike and are not.

  • A broken contract. A null argument, a call in the wrong state, an index off the end: the caller has a bug, and the only recovery is to fix the code. Those stay unchecked — IllegalArgumentException, IllegalStateException, Objects.requireNonNull — and nothing catches them in order to continue.
  • A domain failure. The seat is taken, the balance is short, the record is absent: an outcome the caller must branch on, because the reason changes what it does. That becomes a Result.
  • An environmental failure. IOException when a disk fills, SQLException when a connection drops, a timeout. It is expected in normal operation and it says nothing about the domain. Keep it checked where the call chain never enters a stream or a lambda, and convert it to a domain error at the boundary, so the domain does not depend on java.io.

The three differ in who can act. A bug is fixed by the caller’s author. A domain failure is handled by the caller. An environmental failure is retried, surfaced, or degraded by whatever owns the resource — which is rarely the layer that called the method.

The Result interface below declares only the cases. map, flatMap, and fold are the methods you add to it — map is a switch on this — and each container type needs its own copy, because Java has no higher-kinded types. map transforms a success and passes an error through, flatMap chains a step that can itself fail, and fold takes one handler per branch and returns a single value.

sealed interface Result<T, E> permits Ok, Err {}

record Ok<T, E>(T value) implements Result<T, E> {}

record Err<T, E>(E error) implements Result<T, E> {}

sealed interface LookupError permits NotFound, Unavailable {}
record NotFound(UserId id) implements LookupError {}
record Unavailable(String reason) implements LookupError {}

and the call site is a case analysis, not a chain of throws:

Result<User, LookupError> found = users.find(id);

String label = switch (found) {
    case Ok<User, LookupError>(var user) -> user.displayName();
    case Err<User, LookupError>(var error) -> switch (error) {
        case NotFound ignored -> "unknown user";
        case Unavailable down -> "unavailable: " + down.reason();
    };
};

This substitution costs more to adopt than the others, and its cost lands outside the method that returns the value. A result type in a public signature propagates: every caller must adopt it, and every layer must agree on its shape. That agreement is a coupling of its own. The difference from the old code is that agreement on a sealed type is checked by the compiler, and agreement on an implicit failure vocabulary is checked by nobody.

Three operational costs come with it. A Result carries an error value, not the call chain that produced it, so the diagnostic has to be threaded by hand or re-thrown at the edge. A returned Err is a normal return, so a transactional method commits unless you mark the transaction rollback-only before returning it. And Java has no error-propagation operator (Rust’s ?), so a chain of five flatMap calls reads worse than the imperative early return it replaced. Two or three steps compose well. Beyond that, write the early return.

4 State, and the library types to retire

Instance state has one home: the canonical constructor. A setter, an initializer block, or a registry is a hidden parameter on every call, which is why tests then have to set it up in order.

A record has one canonical constructor, whose parameters are the components in the record header, and an optional compact form of that constructor, which is a body written without a parameter list that validates the components before the fields are set ([19], §8.10).

Retire Write instead Why Since · mechanism
instance state set in field initializers, initializer blocks, and the constructor body one canonical constructor, with the compact form for validation A record establishes its instance state in one place; static state still initializes at first touch ([19], §12.4.1). 16
C8
mutable static field written from more than one path a parameter or a constructor argument, or at 25 a scoped value. A DI-managed singleton is not this. A static written from two places makes test order and call order matter, and nothing in the type says which —
—
Collections.unmodifiableList(...) List.copyOf(...) when the caller must not see later mutation; keep the view when a live read-only view is what you want The copy is a snapshot, and it is shallow. It also rejects null elements, so a collection that legitimately held one throws where the old code did not ([20]). copyOf at 10
C6
HashMap or HashSet where output order matters LinkedHashMap, EnumMap, TreeMap, List HashMap guarantees no iteration order, and Map.of may iterate differently between runs ([21]). 1.4
C5
finalize() try-with-resources, or Cleaner A finalizer delays collection and can resurrect the object. Cleaner cannot, but it is still not prompt, and it does not substitute for closing a resource deterministically [22]. 7, Cleaner at 9
M3
Date, Calendar, SimpleDateFormat java.time types The old classes are mutable, and SimpleDateFormat is not thread-safe. Date also carries an implicit default zone where java.time states it. 8
C2
bare int arithmetic where overflow matters Math.addExact, Math.multiplyExact; long only postpones the overflow Integer addition wraps silently ([19], §15.18.2), and multiplication has its own rule ([19], §15.17.1). A wider type moves the ceiling; addExact and multiplyExact throw at it. 8
Q4
raw type, or Object plus a cast a generic type parameter A raw type removes the check the compiler would otherwise give you. 5
T7

5 Concurrency

Blocking is acceptable again: a virtual thread is cheap enough that a blocking task does not need to become a callback [9]. It is pinned when it is stuck to its operating-system thread, and a pinned thread loses that advantage; since JDK 24 a synchronized block no longer pins, and a native frame on the stack still does [23].

Retire Write instead Why Since · mechanism
new Thread(...), or an unbounded pool (newCachedThreadPool) Executors.newVirtualThreadPerTaskExecutor() for I/O-bound work Virtual threads remove the thread as the scarce resource, not the resource behind it. A fixed pool was also the admission control in front of a connection pool or a rate-limited API, so keep that bound explicit: a Semaphore, a bounded pool, or a queue. 21
K6, removed at 21
ThreadLocal ScopedValue (finalized in 25) [12] The value is bound to a block and released at its end, and a child thread started inside a structured scope inherits it automatically while one started outside does not. It cannot change while the block runs, and work already queued in a pool does not see it. Spring Security’s context, the slf4j MDC, and @Async all still read thread locals, so keep ThreadLocal until each one is bridged [24]. 25
—
synchronized plus wait/notify ReentrantLock plus Condition; better, immutable state and a queue between threads The lock gives you tryLock with a timeout, several wait sets, and an interruptible acquire — not lock discipline, which neither construct checks. Immutable state removes the question. 5
—
Future.get() for a fan-out a block-scoped ExecutorService in try-with-resources ExecutorService is AutoCloseable since Java 19, so close() waits for every task and the block joins the work it launched [25]. A task that never completes blocks it forever. 19
K4, removed at 21

Ship the block-scoped ExecutorService for fan-out. StructuredTaskScope is a preview API that groups subtasks so that none outlives its block; it is on its seventh preview round in Java 27, and a preview needs --enable-preview, so the class files do not load on a stock runtime [2]. The ExecutorService block is the supported version of the same idea, and it is blunter: it waits for every task and reports no failure itself, so a result or a failure is read from the futures the block returns.

6 One module, both shapes

The tables give one substitution at a time. A module applies several at once, and that is where the costs and the wins both live. Here is a booking service in the shape this page retires:

final class Seat {
    private final String id;
    private boolean taken;
    Seat(String id) { this.id = id; }
    String id() { return id; }
    boolean taken() { return taken; }
    void setTaken(boolean taken) { this.taken = taken; }
}

record Booking(String seatId, Instant at) {}

final class BookingService {
    private final Map<String, Seat> seats = new HashMap<>();

    void open(String seatId) {
        seats.put(seatId, new Seat(seatId));
    }

    Booking confirm(String seatId) {
        Seat seat = seats.get(seatId);
        if (seat == null) {
            return null;
        }
        if (seat.taken()) {
            throw new IllegalStateException("seat is taken");
        }
        seat.setTaken(true);      // mutates in place; a listing already returned shows the change
        return new Booking(seatId, Instant.now());
    }

    List<Seat> listing() {
        return List.copyOf(seats.values());
    }
}

Three outcomes leave the method by three routes: a null, a throw, and a value. Two of them are invisible in the signature, the seat mutates under anyone holding it, and HashMap guarantees no order, so the listing follows the keys’ hash codes and the table’s capacity rather than the order the seats were opened.

The same module in the shape this page recommends:

record Seat(String id, boolean taken) {}
record Booking(String seatId, Instant at) {}

sealed interface Confirmation permits Confirmed, SeatNotFound, Rejected {}
record Confirmed(Booking booking) implements Confirmation {}
record SeatNotFound(String seatId) implements Confirmation {}
record Rejected(String reason) implements Confirmation {}

final class BookingService {
    private final Map<String, Seat> seats = new LinkedHashMap<>();

    void open(String seatId) {
        seats.put(seatId, new Seat(seatId, false));
    }

    Confirmation confirm(String seatId) {
        return switch (seats.get(seatId)) {
            case null -> new SeatNotFound(seatId);
            case Seat s when s.taken() -> new Rejected("seat is taken");
            case Seat s -> {
                seats.put(seatId, new Seat(s.id(), true));
                yield new Confirmed(new Booking(seatId, Instant.now()));
            }
        };
    }

    List<Seat> listing() {
        return List.copyOf(seats.values());
    }
}

Every outcome is one case of one return type: absence (SeatNotFound), refusal (Rejected), and success (Confirmed) are different facts. A caller’s switch over Confirmation is checked for exhaustiveness; adding a fourth case to permits stops every such switch until it is handled, and the ordered map gives the listing the same order on every run. case null matches a null selector explicitly, and when guards a case on a condition [8].

What the module gives up is visible in the same few lines. Seat no longer mutates, so a caller that already holds one keeps the stale value and must ask the service again. The write changes form inside confirm: a put replaces the seat instead of mutating it. The map is still not thread-safe — the old version was not either — but a claim-and-replace on a ConcurrentHashMap can be made atomic with compute without a lock discipline, at the cost of the listing order.

7 Where the subset runs out

Six cases the subset does not cover. Each one needs a named exception to the rule, not a silent one.

  1. Hot loops and large buffers. The data-shape table turns every tuple into a record. Where the value escapes into a collection or an interface, that is an allocation and an indirection per element; where the JIT can scalar-replace it, the cost vanishes, so measure before rewriting a kernel.
  2. Designed extension points. sealed is closed by definition, so plugins and service providers keep open interfaces.
  3. Framework-mandated beans. A JPA entity — a class that the persistence provider maps to a table [26] — needs a non-final class that the provider can instantiate empty and populate afterwards. A record is final and sets all its state in the canonical constructor, so it cannot be proxied either. Put an adapter at the edge and keep the domain in records. Jackson, the JSON library, reads records natively from 2.12 [27]; native image still needs the reflection configuration.
  4. Foreign and older APIs. JDBC and servlet containers predate these constructs: they signal absence with null and failure with checked exceptions, chosen so a driver failure cannot pass unnoticed. Those exceptions do not travel through a stream or a lambda, so convert at the boundary.
  5. Bugs and fatal errors. Throw IllegalArgumentException for a broken contract, let NullPointerException and OutOfMemoryError escape, and let assertions fail: they are defects or resource exhaustion, not domain outcomes. An assert runs only with -ea, so it enforces nothing your build does not enable.
  6. A record whose component is itself mutable. Shallow immutability is not immutability: an array component is shared and its equals is identity-based, and a collection component is shared even where its equals is value-based. Where the value has to hold a buffer, a plain class that copies on the way in and out, and compares with Arrays.equals, is the honest shape.

Two things stay out of scope rather than out of reach: a published API that adopts the subset forces every consumer onto that release floor, and virtual threads change what a thread dump and a log correlation id look like. Both are deployment questions, not language ones.

8 The checklist

The 25 items, numbered so a team can cite them. All but one row link to the section that explains it, and that section carries the release and the mechanism; item 25 links to the limit that explains it.

# Do not write Write instead Where the old form stays Section
1 field, getter, setter, equals, hashCode, toString a record JPA entities, framework-bound types, types in a published API Data shape
2 instanceof, then a cast, then accessors a record pattern an open hierarchy you do not control Data shape
3 Visitor over a closed hierarchy sealed interface plus a switch operations added from outside the owning module Data shape
4 Object[], Map<String, Object>, parallel fields a record a map whose keys are only known at run time Data shape
5 null return Optional, an empty collection, or a result type a library that returns null Data shape
6 Optional.get() orElse, map, flatMap, or orElseThrow() where absence is a bug — Data shape
7 double for money long minor units, or BigDecimal — Data shape
8 char, String.length(), substring by index codePointAt, codePoints(), offsetByCodePoints — Data shape
9 throw for an expected failure the result type bugs, fatal errors, framework callbacks Errors
10 try/catch in the middle of a pipeline map, flatMap, fold; past three steps, the early return the boundary adapter Errors
11 throws on a domain method that crosses a lambda the result type a chain that never enters a stream or a lambda Errors
12 Optional or null used to report a failure the result type — Errors
13 instance state set in three places one canonical constructor, with the compact form for validation — State
14 mutable static field written from more than one path a parameter or a constructor argument, or at 25 a scoped value a DI-managed singleton State
15 Collections.unmodifiableList(...) List.copyOf(...) when the caller must not see later mutation a live read-only view, or a collection holding nulls State
16 HashMap or HashSet where output order matters LinkedHashMap, EnumMap, TreeMap, List — State
17 finalize() try-with-resources, or Cleaner — State
18 Date, Calendar, SimpleDateFormat a java.time type a called API that demands Date State
19 bare int arithmetic where overflow matters Math.addExact, Math.multiplyExact — State
20 raw type, or Object plus a cast a generic type parameter a pre-generics interop boundary State
21 new Thread(...), or an unbounded pool Executors.newVirtualThreadPerTaskExecutor() for I/O compute-bound work keeps a bounded pool Concurrency
22 ThreadLocal ScopedValue Spring Security context, slf4j MDC, @Async, queued pool work Concurrency
23 synchronized plus wait/notify ReentrantLock plus Condition, or immutable state — Concurrency
24 Future.get() for a fan-out a block-scoped ExecutorService — Concurrency
25 a sealed type at an extension point an open interface — Limits

A dash in the fourth column means this page knows of no case where the old form is the better choice. Where one exists in your codebase, write it down as a named exception rather than leaving it silent.

The mechanism column of the four tables falls into three classes. 15 rows name a mechanism Java 25 still pays; the construct keeps that cost out of the code you write. 3 rows name a mechanism the platform removed at 21 — T4, K4, K6 — where the row is how to use a cost already gone. 6 rows name no mechanism code: double for money, an instanceof cast, an unnamed tuple, a ThreadLocal, a mutable static, and a lock swap that leaves race detection manual.

Two constructs are absent on purpose. Primitive types in patterns and StructuredTaskScope are previews in Java 27: production code can use them only behind --enable-preview, and the class files then fail to load on a stock runtime.

The numbers are stable. A row added later takes the next number, and the anchor #item-N keeps working for every row already cited.

9 Making it stick

Prose does not enforce itself. The enforcement this page can make mechanical is a compiler plugin that fails the build.

Error Prone runs as a javac plugin [28]. It needs -XDcompilePolicy=simple, --should-stop=ifError=FLOW, the Error Prone and NullAway jars on the processor path, and one -Xplugin argument that carries both the plugin name and its settings. A check is set with -Xep:<Check>:<Severity> and configured with -XepOpt:<Key>=<Value> — those are Error Prone’s flags, not javac’s [29]. On JDK 16 and later it also needs the --add-exports flags that its installation guide lists, because it reads compiler internals.

The javac parameters, with the exports elided for length:

-XDcompilePolicy=simple
--should-stop=ifError=FLOW
-processorpath error_prone_core.jar:nullaway.jar:your-checks.jar
'-Xplugin:ErrorProne -Xep:NullAway:ERROR -XepOpt:NullAway:AnnotatedPackages=com.example -Xep:BanThrow:ERROR -Xep:BanUnorderedCollection:ERROR -Xep:BanMutableStatic:ERROR'
-Werror

Maven, in maven-compiler-plugin. The same flags go into compilerArgs, and the same jars into annotationProcessorPaths:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <release>25</release>
    <compilerArgs>
      <arg>-XDcompilePolicy=simple</arg>
      <arg>--should-stop=ifError=FLOW</arg>
      <arg>-Xplugin:ErrorProne -Xep:NullAway:ERROR -XepOpt:NullAway:AnnotatedPackages=com.example -Xep:BanThrow:ERROR -Xep:BanUnorderedCollection:ERROR -Xep:BanMutableStatic:ERROR</arg>
      <arg>-Werror</arg>
    </compilerArgs>
    <annotationProcessorPaths>
      <path>
        <groupId>com.google.errorprone</groupId>
        <artifactId>error_prone_core</artifactId>
        <version>${error-prone.version}</version>
      </path>
      <path>
        <groupId>com.uber.nullaway</groupId>
        <artifactId>nullaway</artifactId>
        <version>${nullaway.version}</version>
      </path>
      <!-- every processor the project already uses joins this list -->
    </annotationProcessorPaths>
  </configuration>
</plugin>

with the versions pinned in <properties>, and the --add-exports flags from the installation guide added to compilerArgs.

Gradle, with the net.ltgt.errorprone plugin. It builds the -Xplugin argument and the export flags for you, so the check names are the same but the plumbing is not:

plugins {
  id 'net.ltgt.errorprone' version '4.1.0'
}

dependencies {
  errorprone "com.google.errorprone:error_prone_core:${errorProneVersion}"
  errorprone "com.uber.nullaway:nullaway:${nullawayVersion}"
}

tasks.withType(JavaCompile).configureEach {
  options.errorprone {
    error('NullAway')
    error('BanThrow')
    error('BanUnorderedCollection')
    error('BanMutableStatic')
    option('NullAway:AnnotatedPackages', 'com.example')
  }
  options.compilerArgs += ['-Werror']
}

NullAway is a published check that reports a possible null dereference, and it reads JSpecify annotations [30]. The three Ban* checks are yours to write, and each is a small BugChecker: a class that inspects the compiler’s syntax tree and reports a match.

package checks;

import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ThrowTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ThrowTree;
import com.sun.tools.javac.code.Type;

@BugPattern(summary = "A throw where the surrounding layer returns a result type",
            severity = SeverityLevel.ERROR)
public final class BanThrow extends BugChecker implements ThrowTreeMatcher {
    @Override
    public Description matchThrow(ThrowTree tree, VisitorState state) {
        Type thrown = ASTHelpers.getType(tree.getExpression());
        if (thrown == null || isBug(thrown, state)) {
            return Description.NO_MATCH;
        }
        return describeMatch(tree);
    }

    /** An Error, and the two unchecked types that signal a broken contract. */
    private static boolean isBug(Type thrown, VisitorState state) {
        if (ASTHelpers.isSubtype(thrown, state.getSymtab().errorType, state)) {
            return true;
        }
        for (String name : new String[] {
                "java.lang.IllegalArgumentException", "java.lang.IllegalStateException"}) {
            Type bug = state.getTypeFromString(name);
            if (bug != null && ASTHelpers.isSubtype(thrown, bug, state)) {
                return true;
            }
        }
        return false;
    }
}

The other two are the same shape. BanUnorderedCollection implements NewClassTreeMatcher and reports when a constructor’s owner is java.util.HashMap or java.util.HashSet. BanMutableStatic implements VariableTreeMatcher and reports a static field without Flags.FINAL. All three compile against Error Prone 2.36 on JDK 25. BanThrow reports a throw new DomainException(...) and a throw new RuntimeException(...), and lets IllegalArgumentException, IllegalStateException, and OutOfMemoryError through — the three that mean a bug rather than an outcome.

A syntax check is blunt where the rule is conditional. BanUnorderedCollection forbids the constructor, not the reading of an iteration order, and no check can decide whether an order is read. Scope that one per package; do not claim it enforces the conditional rule.

Adopt it in stages. On an existing codebase, a -Werror build fails on the first compile — on the new checks and, where the build already enables -Xlint:deprecation, on every deprecation the code carries. Run the checks at warning severity first and record the count, exclude legacy paths, and turn -Werror on module by module as each one reaches zero.

Once the three checks exist, the build catches null returns (from NullAway), mutable statics, unordered collections, and a throw outside a list you define for bugs, fatal errors, and framework callbacks. It does not catch aliasing (two references to the same mutable object), and it cannot see Kotlin, generated members, reflective writes, or what an agent adds at load time. NullAway assumes unannotated third-party code is non-null rather than unknown, so a library null still passes through. The plugin is a check that only gets stricter over time; it is not a proof.

10 Migrating in order, and what it costs

The substitutions are not equally cheap, and the cheap ones unlock the expensive ones.

  1. Records first. A record swap is local where the type is not part of a published API, and mechanical where equals and toString are not load-bearing. Where they are, it is a behaviour change with no compile error: an entity’s structural equals, a bean used as a HashMap key, a toString used as a metric label.
  2. Sealed types and patterns next. One closed hierarchy per domain concept, each case a record. This is where switch becomes exhaustive, and where the Visitor disappears.
  3. Then errors. A result type changes every signature along a call chain, so it is the first substitution that crosses module boundaries in every caller. Sealed types cross a boundary once, at the type, and leave construction and passing alone; an exhaustive switch over the type still changes.
  4. Then concurrency. Virtual threads and scoped values change how work is scheduled, not how data is shaped. Doing them last keeps one moving part at a time.
  5. Framework boundaries last. Adapters at the JPA and JSON edge are the lowest-risk code in the system and the least urgent to move — but every framework that speaks beans or exceptions needs one, so they are written and kept, not skipped.

Two rows are local to one file: item 6, and item 15 where the caller must not see later mutation. Several more are local to one module. The rest are module-wide or codebase-wide, and two constructs among them change every link in a chain: the result type (items 9 to 12) in every signature, and ScopedValue (item 22) in where a context value is bound. Budget accordingly.

The subset also carries five costs the tables do not show:

  • A larger language. Five constructs to learn and to read in other people’s code. None of them removes the Java 8 form from the codebase you inherit.
  • Two shapes for errors. During migration the codebase carries both exceptions and results. A caller must satisfy a throws clause and a returned Err, and can silently drop one of them. That is worse than either shape alone, which is why migration should move one module at a time.
  • Failure paths without a stack trace. A Result carries an error value, not the chain that produced it; the diagnostic has to be threaded by hand or the failure re-thrown at the edge.
  • Allocation. Optional and Result allocate. The JIT often removes that allocation when the value never escapes the method, and sometimes it does not — a claim worth measuring on your own hot path rather than trusting.
  • Boundary adapters. Every framework that speaks beans or exceptions needs a translation layer, and that layer is code someone maintains.

A subset is a discipline, enforced in part by a build check, not a language change. It lowers what your code pays on the rows it reaches, at the adoption costs above, not what Java costs, because the old construct remains available to the next team. Only a change to the language itself — a construct the compiler gives every project by default — changes what Java costs.

References

[1]
OpenJDK, “JEP 532: Primitive types in patterns, instanceof, and switch (fifth preview).” Java Enhancement Proposal, JDK 27, 2026. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/532
[2]
OpenJDK, “JEP 533: Structured concurrency (seventh preview).” Java Enhancement Proposal, JDK 27, 2026. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/533
[3]
OpenJDK, “JEP 269: Convenience factory methods for collections.” Java Enhancement Proposal, JDK 9, 2017. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/269
[4]
OpenJDK, “JEP 395: records.” Java Enhancement Proposal, JDK 16, 2021. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/395
[5]
OpenJDK, “JEP 394: Pattern matching for instanceof.” Java Enhancement Proposal, JDK 16, 2021. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/394
[6]
OpenJDK, “JEP 409: Sealed classes.” Java Enhancement Proposal, JDK 17, 2021. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/409
[7]
OpenJDK, “JEP 440: Record patterns.” Java Enhancement Proposal, JDK 21, 2023. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/440
[8]
OpenJDK, “JEP 441: Pattern matching for switch.” Java Enhancement Proposal, JDK 21, 2023. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/441
[9]
OpenJDK, “JEP 444: Virtual threads.” Java Enhancement Proposal, JDK 21, 2023. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/444
[10]
OpenJDK, “JEP 431: Sequenced collections.” Java Enhancement Proposal, JDK 21, 2023. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/431
[11]
OpenJDK, “JEP 454: Foreign function & memory API.” Java Enhancement Proposal, JDK 22, 2024. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/454
[12]
OpenJDK, “JEP 506: Scoped values.” Java Enhancement Proposal, JDK 25, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/506
[13]
OpenJDK, “JEP 511: Module import declarations.” Java Enhancement Proposal, JDK 25, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/511
[14]
OpenJDK, “JEP 512: Compact source files and instance main methods.” Java Enhancement Proposal, JDK 25, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/512
[15]
Oracle Corporation, “Class java.util.optional.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html
[16]
Oracle Corporation, “Class java.lang.string.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html
[17]
OpenJDK, “JEP 361: Switch expressions.” Java Enhancement Proposal, JDK 14, 2020. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/361
[18]
Oracle Corporation, “Class java.lang.record.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 07, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html
[19]
J. Gosling, B. Joy, G. Steele, G. Bracha, A. Buckley, and D. Smith, “The java language specification.” Oracle; Java SE 25 Edition, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/javase/specs/jls/se25/html/index.html
[20]
Oracle Corporation, “Interface java.util.list.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 07, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html
[21]
Oracle Corporation, “Interface java.util.map.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html
[22]
Oracle Corporation, “Class java.lang.ref.cleaner.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ref/Cleaner.html
[23]
OpenJDK, “JEP 491: Synchronize virtual threads without pinning.” Java Enhancement Proposal, JDK 24, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://openjdk.org/jeps/491
[24]
Oracle Corporation, “Class java.lang.ScopedValue.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ScopedValue.html
[25]
Oracle Corporation, “Interface java.util.concurrent.ExecutorService.” Java SE 25 and JDK 25 API Specification, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ExecutorService.html
[26]
Jakarta Persistence Working Group, “Jakarta persistence 3.1 specification.” Eclipse Foundation, 2024. Accessed: Nov. 06, 2026. [Online]. Available: https://jakarta.ee/specifications/persistence/3.1/jakarta-persistence-spec-3.1.html
[27]
FasterXML, “Jackson release 2.12.” Project release notes, 2020. Accessed: Nov. 06, 2026. [Online]. Available: https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.12
[28]
Google, “Error prone: installation.” Error Prone documentation, 2026. Accessed: Nov. 06, 2026. [Online]. Available: https://errorprone.info/docs/installation
[29]
Oracle Corporation, “The javac command.” Java SE 25 Tools Reference, 2025. Accessed: Nov. 06, 2026. [Online]. Available: https://docs.oracle.com/en/java/javase/25/docs/specs/man/javac.html
[30]
Uber Technologies, “NullAway: A tool to help eliminate NullPointerExceptions.” Project documentation, 2026. Accessed: Nov. 06, 2026. [Online]. Available: https://github.com/uber/NullAway