Effective Modern Java
Write Java that compiles on the project's JDK and that a careful reviewer would approve. You already know Java. This skill covers what models still get wrong: features newer than the project's release, modern features with non-obvious traps, Effective Java advice that newer releases changed, and "best practices" that break callers when applied to existing code.
Step 1 — Find the Java baseline before writing a line
| Where | What to read |
|---|---|
pom.xml | maven.compiler.release, <release> in maven-compiler-plugin, java.version (Spring Boot parent), maven.compiler.source/target |
build.gradle(.kts) | options.release, java.toolchain.languageVersion, sourceCompatibility |
| Elsewhere | .java-version, .sdkmanrc, .tool-versions, CI setup-java, Dockerfile base image |
Precedence: an explicit release (maven.compiler.release, options.release) wins over the toolchain, which wins over JAVA_HOME. A Gradle toolchain of 21 with options.release = 17 means you write Java 17. Check for --enable-preview in the compiler args. If it's absent, preview features are off-limits, whatever the JDK.
- Libraries consumed by other teams: the declared release is a promise to their JDKs, so never raise it to use a feature. For a newer fast path, use a multi-release JAR or a
Runtime.version().feature()check. - Found → never use a feature newer than that release. If a newer feature would clearly help, write the compatible version and mention the upgrade in one sentence.
- No project / not found → use the version the user named. Otherwise target Java 25 (the latest LTS; 26 and 27 are non-LTS) and state that assumption in one line.
Release gates (final features; this table is the source of truth):
| Release | Usable from here on |
|---|---|
| 17 (LTS) | records, sealed types, instanceof patterns, switch expressions, text blocks, var, Stream.toList(), RandomGenerator, HexFormat |
| 18 | UTF-8 default charset, {@snippet} Javadoc, finalization deprecated for removal |
| 19 | ExecutorService is AutoCloseable; Future.state()/resultNow() |
| 21 (LTS) | pattern switch (when, case null), record patterns, virtual threads, SequencedCollection/Map (getFirst, getLast, reversed), Math.clamp, StringBuilder.repeat |
| 22 | unnamed variables/patterns _, Foreign Function & Memory API |
| 23 | Markdown doc comments /// |
| 24 | stream gatherers (Gatherers.windowFixed/windowSliding/fold/scan/mapConcurrent); synchronized no longer pins virtual threads (JEP 491) |
| 25 (LTS) | ScopedValue, flexible constructor bodies, import module, compact source files + instance main, KDF API |
| 26, 27 | no new language features; HTTP/3 in HttpClient (26) |
| Preview only (through 27) | StructuredTaskScope (final targeted for 28), primitive patterns, StableValue/LazyConstant |
| Never | STR."…" string templates (withdrawn, removed in 23) |
Per-feature notes, JEPs and BAD/GOOD code: references/modern-java.md.
Step 2 — Defaults to apply without being asked
These are for new code. For existing code, Step 3's refactoring rules take precedence. Each default says why, so you can deviate when the reason doesn't apply. When you do, say so.
Types
- Values are records. Validate in the compact constructor and copy mutable components there (
items = List.copyOf(items)). OverridetoStringwhen a component is secret. Not for JPA entities, mutable state, or identity types. - Closed alternatives → sealed interface + records. On 21+, consume them with a
switchexpression with nodefault, so adding a variant breaks the build everywhere it matters. On 17 there's no pattern switch: put an abstract method on the interface, or use a visitor, to get the same compile-time guarantee. Aninstanceofchain ending inthrowgives no guarantee. - Fixed constant sets → enums with data and behavior;
EnumMap/EnumSet; never compute with or persistordinal(). - Money →
BigDecimalbuilt fromString/valueOf, with an explicitRoundingModeon every division or rate. AMoneyrecord that stores amounts at currency scale must normalize scale in its compact constructor, or the generatedequalssays2.0 ≠ 2.00. Useamount.setScale(digits, RoundingMode.UNNECESSARY): it rejects10.005 USDinstead of silently rounding it. GuardCurrency.getDefaultFractionDigits() < 0(XAU, XXX). Unit prices and FX rates that need more precision belong in a separate type. - IDs, codes, quantities → small records or enums (
OrderId,Weight), not bareString/double. Inject aClockwhere tests need "now".
APIs
- Make classes
finalorsealedunless designed for extension. Exception: classes a framework must proxy (Spring@Configurationand class-based@Transactional/@Asyncbeans, JPA entities) must stay non-final. - Return empty collections, never
null.Optionalonly as a return type: not fields, parameters or elements, and no bareget(). If the project uses JSpecify, follow its annotations.
Errors and resources
- No empty catch, no
e.printStackTrace(), noSystem.out"handling". Log through the project's logger and recover, or rethrow with the cause attached. An intentionally ignored exception is namedignored(or_on 22+) and gets a comment explaining why. InterruptedException: propagate it, or callThread.currentThread().interrupt()before translating it. Never swallow it. For APIs called from request handlers, translating to an unchecked exception after restoring the flag is usually friendlier than a checkedthrows.- try-with-resources for every
AutoCloseablescoped to a method. Long-lived ones, such as a component's executor, close at shutdown.
Concurrency
- Blocking I/O fan-out on 21+ → virtual threads (
Executors.newVirtualThreadPerTaskExecutor()); never pool them; cap a fragile downstream with aSemaphore. ExecutorService.close()waits for submitted tasks to finish. On 25 that includes tasksinvokeAllalready cancelled. A per-calltry (var ex = …)therefore doesn't bound latency when a callee ignores interrupts, and many HTTP/JDBC clients do. For deadline-bound fan-out, keep a long-lived executor (shut down at exit withshutdownNow()plus a boundedawaitTermination) and useinvokeAll(tasks, timeout, unit), which cancels stragglers at the deadline. Don't callf.get(2, SECONDS)in a loop: the worst case is N × 2s. Cancelled-but-uninterruptible calls keep running in the background, so tell the user the client's own connect/read timeouts are what actually bound them.- When the code runs on JDK 21–23, don't block inside
synchronizedon virtual threads (it pins the carrier); useReentrantLock. JDK 24+ fixed this. The runtime JDK decides, not--release. - Check-then-act on shared state needs an atomic operation:
Set.add's return value,putIfAbsent,computeIfAbsent. AConcurrentHashMapdoesn't makeif (!m.containsKey(k)) m.put(k, v)safe. ScopedValue(25) replacesThreadLocalfor context passed down a call chain. It is not inherited by tasks you submit to an executor, only byStructuredTaskScopeforks, which are preview. Rebind it inside the task if needed. MDC, security and transaction context still live inThreadLocals today.
Pitfalls models hit with modern Java
| Trap | What happens | Do instead |
|---|---|---|
Arrow-form switch statement over an enum | Not checked for exhaustiveness. A missing case compiles and silently does nothing. | Use a switch expression. On 21+, adding case null -> throw … makes the statement exhaustiveness-checked too |
default in a switch over a sealed type or enum you own | Hides new variants from the compiler | Leave default out. For third-party or externally sourced enums, tolerating unknown constants is correct |
Wrapped one-line prose ("a " + "b") turned into a text block | Every source line break becomes \n, a closing """ on its own line adds a trailing \n, and the common leading indentation, including a space that started a piece, is stripped. Tool descriptions, messages and test expectations change silently | End each line with \ and put the space before it; put the closing """ on the last content line; write a leading space on the first line as \s. Prove the value is unchanged (compare the old and new constants) |
| Code compiled against an old sealed hierarchy | New subtype at runtime → MatchException | Recompile dependents; treat new variants as breaking |
Stream.toList() vs Collectors.toList() vs toUnmodifiableList() | toList() is unmodifiable but allows nulls; toUnmodifiableList() throws NPE on null; Collectors.toList() makes no mutability promise | Use toList() only when callers don't mutate; else toCollection(ArrayList::new) |
List.of / List.copyOf / Map.of | Reject null elements; List.of(..).contains(null) throws NPE; Map.of throws on duplicate keys | Filter nulls first or use another collection; toMap(k, v, merge) for duplicates |
Collections.unmodifiableList(list) | A view: later changes to list show through | List.copyOf(list) for a snapshot |
| Record with an array component | equals/hashCode compare the array by reference | Use List, or override both |
list.reversed() (21) | A live view, not a copy | List.copyOf(list.reversed()) for a snapshot |
getFirst() on an empty list | NoSuchElementException | Check isEmpty() |
Optional.orElse(expensive()) | The argument is evaluated even when a value is present | orElseGet(() -> expensive()) |
Integer a == b | Reference comparison; works only for −128..127 | equals, or primitives |
new BigDecimal(0.1) | Captures the binary error (0.1000000000000000055…) | new BigDecimal("0.1") / BigDecimal.valueOf(0.1) |
Shared static SimpleDateFormat | Corrupted output under concurrency | A DateTimeFormatter constant |
One RandomGenerator from RandomGeneratorFactory (e.g. L64X128MixRandom) shared across threads | These algorithms aren't thread-safe | One instance per thread, or ThreadLocalRandom.current() |
javax.xml.bind (JAXB), Nashorn, reflection into java.* internals | Removed from the JDK (11, 15) or blocked since 17: fails at runtime, not always at compile time | Explicit Jakarta/Nashorn dependencies; supported APIs (see modern-java.md#avoid) |
Step 3 — Workflow by task
Writing new code. Find the baseline (Step 1). Design the types first, then the behavior. Add tests for the behavior. Then verify (below).
Verify, don't assume. Run the project's build (./mvnw verify, ./gradlew build, or the system mvn/gradle if there's no wrapper). With no build, compile with javac --release <N> -Xlint:all, adding -cp for any dependencies. Use --release, not -source: it also rejects APIs newer than N, such as List.getFirst() under 17. A clean compile at the right release proves Step 1 held.
Refactoring and modernizing existing code. Preserve observable behavior, because that's the contract.
- If there are no tests, first write characterization tests against the original code, then keep them green.
- Target the project's baseline unless the user asked for an upgrade. Change one concern at a time.
- Sweep the mechanical idioms the baseline already allows, even when the release isn't changing. Seeing records and pattern
switchin a codebase doesn't mean the sweep was done, so grep for the old forms (patterns inreferences/modern-java.md#idioms). Each conversion keeps behavior:- string literals concatenated across lines → a text block, including annotation attributes (a text block is a compile-time constant). Wrapped one-line prose stays one line only if you use
\at each line end; see Pitfalls; - JSON, XML, SQL or YAML packed onto one line, in a text block or an escaped literal (
"{\"id\":1}") → a text block laid out the way a reader scans it (nested structure indented, one XML element per line). Do this only where the consumer ignores that whitespace, such as a parser, Solr's update handler, or a test fixture that is parsed before it is asserted on. Leave strings that are compared or forwarded verbatim as they are, such as tool descriptions, golden-file expectations and signed payloads. Prove it by parsing the old and new forms and comparing the values; instanceof Tfollowed by a(T)cast →instanceof T t;- a statement
switchthat only assigns or returns → aswitchexpression; - manual
finally { close() }→ try-with-resources; raw types → generics; explicit type arguments →<>; collect(Collectors.toList())whose result is never mutated →toList().
- string literals concatenated across lines → a text block, including annotation attributes (a text block is a compile-time constant). Wrapped one-line prose stays one line only if you use
- Keep public signatures source-compatible unless the user asked for API changes. Modernize behind them: generics, try-with-resources, enums, and
BigDecimal/java.timeinternally. Records are for new internal types. - Fix real bugs even if behavior shifts, such as a missing
hashCode, swallowed exceptions, leaks, ornullmeaning "none". List each one. - Offer contract changes as a follow-up with a migration path. Examples:
double→BigDecimalreturn types, a mutable class → record,Date→Instantin signatures. The usual path is a new method next to a@Deprecatedold one. - Watch for new overloads that make existing calls ambiguous. For example, adding
m(Category)besidem(String)breaksm(null). - In the summary, separate breaks callers' compilation, runtime behavior changes, and kept on purpose.
Upgrade order and OpenRewrite recipes: references/modern-java.md#upgrade.
Reviewing.
- Order findings by severity: correctness and concurrency bugs first, then API and design, then a short modernization and style list. Short means one line per idiom from the Step 3 sweep, with a count and an example
file:line, not one line per site. Short doesn't mean leaving idioms out. - For each finding give
file:line, the concrete consequence (what breaks, for whom), and the fix. End with the minimum set to fix before merge. - Cite an Effective Java item (
EJ 11) only where the reasoning is non-obvious; tagging every line is noise. - Don't rewrite the code unless asked, and don't nitpick what the formatter owns. The formatter owns where lines wrap. Whether a string is a
+chain or a text block is your call, not the formatter's.
Step 4 — Self-check
- Every feature is final in the project's release (or preview is enabled), and the code compiled at that release.
- Every switch over an enum or sealed type you own is an exhaustive expression or pattern switch with no
default. - Concurrent code: deadlines actually bound latency; check-then-act is atomic.
- Refactors: public signatures unchanged unless asked, and every behavior change listed.
- Refactor, modernize and review passes: grepped for every mechanical idiom in Step 3, then converted or reported each one. Converted strings are identical to the originals, and reformatted JSON/XML payloads parse to the same values.
References
references/modern-java.md: Java 17 → 25 feature guide. JEPs, BAD/GOOD code, preview and withdrawn APIs, and a safe upgrade order. Read it when using any feature newer than Java 11, or when upgrading code.references/effective-java.md: all 90 Effective Java (3rd ed.) items marked Applies / Refined / Superseded, each with its modern note, plus worked before/after examples (tagged class → sealed, value class → record, virtual-thread fan-out with deadlines, and more). Read it when reviewing, or when you need the reasoning behind a default.