Video in progress

You're migrating a large codebase from Java 8 to Java 21. What risks and opportunities related to stream and lambda code do you put in the plan?

Risks: places where behavior changed (count() skipping peek, automatic replacement with toList(), Set.of ordering, changes in libraries), and pinning with virtual threads. Opportunities: simpler pipelines with toList, takeWhile, teeing, mapMulti, records and pattern matching. I first only raise the version, and do modernization separately, in small steps.

📖 Answer

The main principle: don't mix migration and refactoring in one PR. First the code has to work on Java 21 exactly as before, and only then the new features.

Places where behavior may change:

  • The count() optimization (Java 9+): on a SIZED source the pipeline may not run, and side effects inside peek or map silently disappear. Search the codebase for peek( and review each one.
  • Automatic refactoring: the IDE suggests collect(Collectors.toList()) → toList(). The result becomes unmodifiable, and a later add/sort breaks at runtime. I ban bulk replacement, or allow it only where it's proven the result isn't modified.
  • Immutable factories: Collectors.toUnmodifiable* and List.of don't accept null. If old code has a null element, you get an NPE.
  • Order: HashMap's internal structure already changed in Java 8, but if you move to Set.of/Map.of, iteration order is different on every start, and tests that rely on order become flaky.
  • Libraries: old versions of Lombok, Mockito, ByteBuddy and ASM don't know the new bytecode; the move of lambdas to hidden classes (Java 15) affected some agents and profilers.
  • The module system: code that reaches into JDK internals via reflection (needs --add-opens).

Opportunities (the next stage, by impact):

  • record + stream: short, immutable types for DTOs and intermediate results;
  • Stream.toList(), Collectors.teeing, takeWhile/dropWhile, Optional.orElseThrow(), Optional.or;
  • pattern matching instanceof/switch: instead of filter(x -> x instanceof A).map(x -> (A) x);
  • virtual threads for I/O fan-out instead of parallel streams. But blocking inside synchronized pins the carrier in Java 21–23; until Java 24, check with -Djdk.tracePinnedThreads or JFR.

The plan:

  1. Build and tests on two JDKs in CI (8 and 21) during the transition.
  2. A canary deploy, comparing GC and latency metrics (the default GC changed too: G1).
  3. Modernization with OpenRewrite recipes, but each recipe as its own PR with review.

In such migrations, what takes the most time isn't the code but the reliability of the libraries and the tests.