| JEP | Feature | Status in 25 | Example on this page |
|---|---|---|---|
| 506 | Scoped Values | Final | Yes |
| 510 | Key Derivation Function API | Final | Yes |
| 511 | Module Import Declarations | Final | Yes |
| 512 | Compact Source Files and Instance Main Methods | Final | Yes |
| 513 | Flexible Constructor Bodies | Final | Yes |
| 519 | Compact Object Headers | Product feature | Yes |
| 521 | Generational Shenandoah | Product feature | Yes |
| 514 | Ahead-of-Time Command-Line Ergonomics | Final | Yes |
| 515 | Ahead-of-Time Method Profiling | Final | Yes (same demo as 514) |
| 520 | JFR Method Timing & Tracing | Final | Yes |
| 518 | JFR Cooperative Sampling | Final | No (an internal sampling change) |
| 503 | Remove the 32-bit x86 Port | Final | No (a platform removal) |
| 509 | JFR CPU-Time Profiling | Experimental | Yes |
| 507 | Primitive Types in Patterns, instanceof, and switch | Third preview | Yes |
| 505 | Structured Concurrency | Fifth preview | Yes |
| 502 | Stable Values | Preview | Yes |
| 470 | PEM Encodings of Cryptographic Objects | Preview | Yes |
| 508 | Vector API | Tenth incubator | Yes |
Tested against. Eclipse Temurin 25.0.5.1+2. The JEP list and the 16 September 2025 GA date come from the JDK 25 project page and the Oracle release notes; the project page itself labels only some JEPs with a stage, so the statuses for the rest come from each JEP’s own page and from what the compiler and launcher accepted. Preview demos are compiled with--release 25 --enable-preview. The runnable project is the java25-features module;./run.shregenerates every output quoted here. There is no separate docs folder: the deeper material sits in the expandable sections of this page.
What is final, what is preview
--enable-preview or --add-modules to compile, or may change. The count of 12 green JEPs matches the heise report that twelve of the eighteen are final. The rest of this page goes in the order a developer meets them: language first, then libraries, then the JVM and tooling changes that need no code at all.
Go deeper: how I decided what counts as final
The JDK 25 project page does not use the word “final” for any JEP, and it was still listing some JEPs under “proposed to target” when I read it, so it cannot be the only source. I took the stage of each JEP from the JEP page itself, then checked the claim that matters to you, does it compile and run without a flag, by running it. That is why the tables here say “Product feature” for compact object headers and generational Shenandoah: both ran with a plain -XX:+ flag and no UnlockExperimentalVMOptions, which the transcripts below show.
The earlier version of this page was a Java 21 to 25 upgrade tour and is kept further down, unchanged, in its own expandable section. For the upgrade itself (build files, Lombok, jdeps, AI prompts) see the Java 21 to 25 upgrade guide.
- JDK 25 project page
- Oracle JDK 25 release notes
- Java 21 Features with Examples — the previous LTS, same format
Write a first program without the ceremony: compact source files and module imports
Until Java 25, “hello world” needed a public class, apublic static void main(String[] args) and System.out.println, which a beginner has to be told to ignore. A compact source file (JEP 512, final in 25) drops all three: the file holds methods and fields directly, and main can be an instance method with no arguments. Run it straight from the source file with java Hello.java. The file is Hello.java:
// JEP 512 (final in 25): a compact source file. No class, no static, no String[] args, no System.out.
String greet(String who) { return "Hello, " + who; }
void main() {
IO.println(greet("Java 25"));
IO.println("class name the launcher gave me: " + getClass().getName());
}
Its real output, from 03-compact-source.txt:
$ java src/Hello.java (25.0.5.1)
Hello, Java 25
class name the launcher gave me: Hello
The launcher wrapped the methods in a class named after the file. IO.println comes from the new java.lang.IO class (javap java.lang.IO on JDK 25 lists it), so it needs no import in any file.
The second small change is the module import declaration (JEP 511, final in 25): import module java.base; imports every public type of every package that module exports, so List, Map, Stream, Path and LocalDate need no individual imports. The program is ModuleImportDemo.java:
import module java.base; // JEP 511 (final in 25): every public type of every package java.base exports
/** No import for List, Map, Stream, Path, LocalDate or Collectors: the one line above covers them. */
public class ModuleImportDemo {
public static void main(String[] args) {
List<String> words = List.of("alpha", "beta", "gamma", "delta");
Map<Integer, List<String>> byLen = words.stream().collect(Collectors.groupingBy(String::length));
System.out.println(byLen);
System.out.println(Path.of("/tmp", "x.txt") + " " + LocalDate.of(2025, 9, 16));
}
}
Output from 02-module-import.txt:
{4=[beta], 5=[alpha, gamma, delta]}
/tmp/x.txt 2025-09-16
The trap: two modules can export the same simple name. Importingjava.baseandjava.sqltogether makesDateambiguous, becausejava.util.Dateandjava.sql.Dateboth match. The compiler’s own message is quoted in the common-mistakes section below. The fix is one ordinary single-type import such asimport java.util.Date;, which wins over the module import.
Go deeper: what a compact file really is, and when to stop using one
A compact source file is still an ordinary class underneath. The compiler wraps the top-level methods and fields in an implicitly declared final class named after the file, which is why getClass().getName() printed Hello above. In that kind of file the java.base module is imported automatically: a one-line check on JDK 25, void main() { List<String> l = List.of("a","b"); IO.println(l.stream().collect(Collectors.joining("+"))); } in a file with no imports, printed a+b. That is a convenience for teaching and scripts; once a file needs a package, a second class or a test, make it a normal class.
The launcher also finds main by a new order: a static main(String[]) still wins, then static main(), then the instance forms, so existing programs behave exactly as before. Module imports are purely a compile-time shortcut: the class file records ordinary imports, so nothing changes at run time.
- JEP pages: JEP 512, JEP 511
- Source: src/ModuleImportDemo.java
- Java 21 Features with Examples covers the preview that became this feature (unnamed classes and instance main, JEP 445)
Validate and set fields before super(): flexible constructor bodies
A constructor used to have to call super(...) or this(...) as its very first statement, so validation had to hide in a helper method inside the call. JEP 513 (final in 25) lets statements run before that call, provided they do not read this. The picture shows the bug this fixes: a parent constructor that calls an overridden method sees the child’s fields still at their defaults.
/** JEP 513 (final in 25): statements may run before super(...) as long as they do not touch `this`. */
public class FlexibleConstructorDemo {
static class Shape {
final String describe;
Shape() { this.describe = describe(); } // calls an overridden method from the super constructor
String describe() { return "shape"; }
}
static class Square extends Shape {
final int side;
Square(int side) {
if (side <= 0) throw new IllegalArgumentException("side must be positive, got " + side); // before super()
this.side = side; // assigning a field before super() is allowed
super();
}
@Override String describe() { return "square side=" + side; } // sees side, not the default 0
}
static class Old extends Shape {
final int side;
Old(int side) { super(); this.side = side; }
@Override String describe() { return "old square side=" + side; }
}
public static void main(String[] args) {
System.out.println(new Square(4).describe);
System.out.println(new Old(4).describe);
try { new Square(-1); } catch (IllegalArgumentException e) { System.out.println("rejected: " + e.getMessage()); }
}
}
Output from 04-flexible-constructor.txt:
square side=4
old square side=0
rejected: side must be positive, got -1
You still cannot touchthisbeforesuper(). Calling an instance method there is rejected: the compiler says it cannot referencedescribe()before the supertype constructor has been called. The exact message is in the common-mistakes section. Assigning a field of the same class is the one exception.
Go deeper: the two phases of a constructor
JEP 513 describes a constructor as having a prologue (the code before the super(...) or this(...) call) and an epilogue (everything after). In the prologue you may declare locals, validate arguments, compute values to pass to the parent and assign fields declared by your own class; you may not read fields, call instance methods or use this in any other way. The earlier trick, a static helper that throws, still compiles, so nothing existing breaks.
The classic win is the pattern in the demo: validate first so an invalid object never reaches the parent constructor, and initialise a field the parent will observe through an overridable method. If you maintain a class hierarchy that does the second thing, it is worth knowing that reordering is now possible, but also that calling overridable methods from constructors remains a design smell.
- JEP page: JEP 513
- Source and output: src/FlexibleConstructorDemo.java, output/04-flexible-constructor.txt
- Earlier previews: JEP 447 (22), 482 (23), 492 (24)
Pass a value down a call tree without a parameter: scoped values
AThreadLocal is a global slot per thread that you must remember to clear. A scoped value (JEP 506, final in 25) is bound for exactly the duration of a call: code inside ScopedValue.where(...).run(...) can read it, and when the call returns the binding is gone, so there is nothing to clean up. Rebinding inside creates a nested scope and restores the outer value afterwards. The demo is ScopedValuesDemo.java:
/** JEP 506 (final in 25): a value bound for the duration of a call, visible to everything called inside it. */
public class ScopedValuesDemo {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static void audit(String action) {
System.out.println(action + " by " + (USER.isBound() ? USER.get() : "nobody"));
}
static void deleteAccount() { audit("delete account"); }
public static void main(String[] args) throws Exception {
audit("before"); // not bound yet
ScopedValue.where(USER, "alice").run(() -> {
deleteAccount(); // sees alice with no parameter passing
ScopedValue.where(USER, "admin").run(() -> audit("nested rebind"));
audit("after nested"); // back to alice
});
audit("after"); // binding is gone
String r = ScopedValue.where(USER, "bob").call(() -> "call returned for " + USER.get());
System.out.println(r);
}
}
Output from 01-scoped-values.txt:
before by nobody
delete account by alice
nested rebind by admin
after nested by alice
after by nobody
call returned for bob
deleteAccount() never received the user as a parameter and still printed alice; the nested admin binding ended before the next line, which printed alice again; and after the outer run the value was unbound.
Go deeper: why not just ThreadLocal, and what changed since the preview
A ThreadLocal is mutable, lives as long as its thread (a problem with pooled threads and with millions of virtual threads), and a child thread can inherit a copy only through InheritableThreadLocal. A scoped value is immutable inside its scope, is bound by structure, and is cheap to inherit into the threads a structured scope forks. That is why the two JEPs travel together: scoped values are what StructuredTaskScope forks inherit.
The binding methods used above are ScopedValue.where(KEY, v).run(...) and .call(...). The earlier version of this page, kept in the expandable section at the bottom, shows a ThreadLocal to ScopedValue migration run on several JDKs.
- JEP page: JEP 506
- Standalone deep dive with memory measurements: the scoped-values module
- Source and output: src/ScopedValuesDemo.java, output/01-scoped-values.txt
Match on int and long, not just objects: primitive patterns (preview)
JEP 507 (third preview in 25) lets instanceof and switch use primitive types in patterns. In an instanceof the test is true only if the conversion is exact, so long v instanceof int i asks “does this long fit in an int without losing anything”. Compile with --release 25 --enable-preview. The source is PrimitivePatternsPreview.java:
/** JEP 507 (third preview in 25): primitive types in instanceof and switch patterns. Needs --enable-preview. */
public class PrimitivePatternsPreview {
static String bucket(int status) {
return switch (status) {
case 200 -> "ok";
case int i when i >= 500 -> "server error " + i; // a primitive type pattern with a guard
case int i when i >= 400 -> "client error " + i;
case int i -> "other " + i;
};
}
static String fits(long v) {
if (v instanceof int i) return v + " fits in int as " + i; // true only if the conversion is exact
return v + " does not fit in int";
}
public static void main(String[] args) {
System.out.println(bucket(200) + " | " + bucket(503) + " | " + bucket(404) + " | " + bucket(302));
System.out.println(fits(42L));
System.out.println(fits(5_000_000_000L));
double d = 3.0, e = 3.5;
System.out.println(d + " instanceof int? " + (d instanceof int) + ", " + e + " instanceof int? " + (e instanceof int));
int small = 16_777_216, big = 16_777_217; // 2^24 is exact as a float, 2^24+1 is not
System.out.println(small + " instanceof float? " + (small instanceof float) + ", " + big + " instanceof float? " + (big instanceof float));
}
}
Output from 06-primitive-patterns.txt:
ok | server error 503 | client error 404 | other 302
42 fits in int as 42
5000000000 does not fit in int
3.0 instanceof int? true, 3.5 instanceof int? false
16777216 instanceof float? true, 16777217 instanceof float? false
Without the flag it does not compile. The compiler’s message, “primitive patterns are a preview feature and are disabled by default”, is quoted in the common-mistakes section. Preview class files also refuse to load on a JDK of a different feature release.
Go deeper: what “exact” means
The conversion is exact when no information is lost: 5_000_000_000L does not fit an int, 3.5 does not convert to an integer, and 16777217 cannot be represented as a float even though 16777216 can, which the last line of the output shows. That precision rule is why this is useful for range checks and for safe narrowing without writing the bounds by hand. The switch form also allows primitive selectors of types that were previously not permitted, such as long, with the usual exhaustiveness checking.
It is a preview for the third time, so its rules for what the compiler accepts may still change before it is final. Do not ship it in a library compiled against a preview release.
- JEP page: JEP 507
- Source and output: src/PrimitivePatternsPreview.java, output/06-primitive-patterns.txt
- Pattern switch fundamentals: Java 21 Features with Examples
Compute it once, then treat it as a constant: stable values (preview)
A stable value (JEP 502, preview in 25) is a holder that is empty until first use, is filled at most once even with many threads asking, and can then be treated by the JVM like afinal field. It replaces the lazy-holder class idiom and the double-checked-locking field. The demo counts how many times the expensive function actually runs. Source: StableValuesPreview.java:
import java.util.List;
import java.util.function.Supplier;
/** JEP 502 (preview in 25): StableValue, a value that is computed at most once and then treated as a constant. Needs --enable-preview. */
public class StableValuesPreview {
static int calls = 0;
static String expensive() { calls++; return "config loaded (call #" + calls + ")"; }
static final Supplier<String> CONFIG = StableValue.supplier(StableValuesPreview::expensive);
static final List<String> SQUARES = StableValue.list(5, i -> { calls++; return "sq(" + i + ")=" + i * i; });
public static void main(String[] args) {
System.out.println("calls before first use: " + calls);
System.out.println(CONFIG.get());
System.out.println(CONFIG.get());
System.out.println("calls after two gets: " + calls);
System.out.println(SQUARES.get(3));
System.out.println(SQUARES.get(3));
System.out.println("calls after list use: " + calls + " (one element computed, four not)");
StableValue<String> sv = StableValue.of();
System.out.println("trySet first: " + sv.trySet("a") + ", trySet second: " + sv.trySet("b") + ", value: " + sv.orElseThrow());
}
}
Output from 07-stable-values.txt:
calls before first use: 0
config loaded (call #1)
config loaded (call #1)
calls after two gets: 1
sq(3)=9
sq(3)=9
calls after list use: 2 (one element computed, four not)
trySet first: true, trySet second: false, value: a
Two get() calls ran the loader once, and the list computed only the element asked for, not all five.
Go deeper: it was renamed after 25
This API did not stay as it is here. The repository’s chapter on the later preview names it lazy constants (JEP 531, third preview, with LazyConstant.of(...)), and the Java 27 post walks through the move. If you adopt stable values on 25 treat it as an experiment: the idea survives, the method names did not.
- JEP page: JEP 502
- Later form: lazy constants chapter
- Source and output: src/StableValuesPreview.java, output/07-stable-values.txt
Run subtasks as one unit: structured concurrency (fifth preview)
A structured task scope (JEP 505, fifth preview in 25) treats several concurrent subtasks as one operation: you fork them, join them, and leave the block only when every one has finished or been cancelled. In 25 you open a scope withStructuredTaskScope.open() and choose what “done” means with a Joiner: the default waits for all and fails fast, anySuccessfulResultOrThrow() returns the first success and cancels the rest. The demo has all three cases: StructuredConcurrencyPreview.java:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
/** JEP 505 (fifth preview in 25): open() and Joiner replace the shutdown-policy subclasses. Needs --enable-preview. */
public class StructuredConcurrencyPreview {
static String fetch(String name, long ms) throws InterruptedException { Thread.sleep(ms); return name + " after " + ms + "ms"; }
public static void main(String[] args) throws Exception {
try (var scope = StructuredTaskScope.open()) { // default Joiner: all must succeed
Subtask<String> a = scope.fork(() -> fetch("user", 50));
Subtask<String> b = scope.fork(() -> fetch("orders", 80));
scope.join();
System.out.println(a.get() + " | " + b.get());
}
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow())) { // first result wins
scope.fork(() -> fetch("slow mirror", 400));
scope.fork(() -> fetch("fast mirror", 30));
System.out.println("winner: " + scope.join());
}
try (var scope = StructuredTaskScope.open()) { // one failure cancels the rest
scope.fork(() -> fetch("long task", 2000));
scope.fork(() -> { throw new IllegalStateException("boom"); });
scope.join();
} catch (Exception e) {
System.out.println("join threw " + e.getClass().getSimpleName() + " caused by " + e.getCause());
}
}
}
Output from 08-structured-concurrency.txt:
user after 50ms | orders after 80ms
winner: fast mirror after 30ms
join threw FailedException caused by java.lang.IllegalStateException: boom
Still a preview, so keep it out of shared libraries. It was still a preview in 25 and the earlier version of this page ran it on 26 and 27 as well: the API moved between releases, and code written against the 21 preview’s ShutdownOnFailure does not compile on 25: the compiler says it cannot find that class, quoted in the common-mistakes section.
Go deeper: what the failure case shows
In the third block of the demo one subtask throws immediately while another sleeps for two seconds. join() threw a FailedException whose cause is the original IllegalStateException, and the long task was cancelled rather than waited for. That cancel-on-failure behaviour is the reason to prefer a scope over a hand-rolled ExecutorService plus Future.get() loops, where the second task keeps running after the first has failed.
Because forks run on virtual threads and inherit scoped values, this pairs with the scoped-values section above. For the virtual-thread side see the virtual threads benchmarks.
- JEP page: JEP 505
- Longer treatment: Structured Concurrency in Java
- Source and output: src/StructuredConcurrencyPreview.java, output/08-structured-concurrency.txt
Derive keys and read PEM text with standard APIs: KDF (final) and PEM (preview)
Deriving several keys from one secret used to mean a third-party library or hand-written HMAC loops. The Key Derivation Function API (JEP 510, final in 25) addsjavax.crypto.KDF with HKDF built in. The demo derives 42 bytes with HKDF-SHA256 and compares them with the published test vector from RFC 5869: KdfDemo.java:
import javax.crypto.KDF;
import javax.crypto.spec.HKDFParameterSpec;
import java.util.HexFormat;
/** JEP 510 (final in 25): HKDF through the new javax.crypto.KDF API, checked against RFC 5869 test case 1. */
public class KdfDemo {
public static void main(String[] args) throws Exception {
HexFormat hex = HexFormat.of();
byte[] ikm = hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
byte[] salt = hex.parseHex("000102030405060708090a0b0c");
byte[] info = hex.parseHex("f0f1f2f3f4f5f6f7f8f9");
KDF kdf = KDF.getInstance("HKDF-SHA256");
byte[] okm = kdf.deriveData(HKDFParameterSpec.ofExtract().addIKM(ikm).addSalt(salt).thenExpand(info, 42));
String expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865";
System.out.println("OKM " + hex.formatHex(okm));
System.out.println("RFC 5869 " + expected);
System.out.println("match " + hex.formatHex(okm).equals(expected));
}
}
Output from 05-kdf.txt:
OKM 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
RFC 5869 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
match true
The second crypto change is PEM encodings (JEP 470, preview in 25): PEMEncoder and PEMDecoder convert keys and certificates to and from the -----BEGIN ...----- text format without Bouncy Castle or manual Base64. Needs --enable-preview. Source: PemPreview.java:
import java.security.*;
/** JEP 470 (preview in 25): encode and decode keys as PEM text. Needs --enable-preview. */
public class PemPreview {
public static void main(String[] args) throws Exception {
KeyPairGenerator g = KeyPairGenerator.getInstance("Ed25519");
KeyPair kp = g.generateKeyPair();
String pem = PEMEncoder.of().encodeToString(kp.getPublic());
System.out.println(pem);
PublicKey back = PEMDecoder.of().decode(pem, PublicKey.class);
System.out.println("round trip equal: " + back.equals(kp.getPublic()));
System.out.println("private key header: " + PEMEncoder.of().encodeToString(kp.getPrivate()).lines().findFirst().orElse(""));
}
}
Output from 09-pem.txt (the key is generated fresh on every run, so the Base64 line will differ when you run it):
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAKBmGVhQYHIYYS9a5T+AJ8IcxKzPBdjXHOrHxoNCp0EQ=
-----END PUBLIC KEY-----
round trip equal: true
private key header: -----BEGIN PRIVATE KEY-----
Go deeper: where each one fits
HKDF is the extract-and-expand function from RFC 5869. The demo’s equality with the RFC’s own test case is a stronger statement than “it produced bytes”: it proves the new API implements the standard. The standalone HKDF post covers per-tenant keys and interoperability with Python and OpenSSL.
PEM is a preview, so use it for tools and experiments in 25. The round trip in the demo decodes the text back into a PublicKey that equals the original, and the private key encodes as a PRIVATE KEY block (PKCS#8). Encrypted private keys and certificate bundles are also in scope of the JEP.
- JEP pages: JEP 510, JEP 470
- Key Derivation Function API in Java (JEP 510)
- Sources: src/KdfDemo.java, src/PemPreview.java
SIMD from Java: the Vector API (tenth incubator)
The Vector API (JEP 508, tenth incubator in 25) lets Java express operations on several array elements per CPU instruction. It stays in an incubator module until the value-class work it depends on lands, so it needs--add-modules jdk.incubator.vector and prints a warning. The demo is a dot product with a scalar tail loop, checked against a plain loop: VectorDemo.java:
import jdk.incubator.vector.*;
/** JEP 508 (tenth incubator): sum of products with lanes. Needs --add-modules jdk.incubator.vector. */
public class VectorDemo {
static final VectorSpecies<Float> S = FloatVector.SPECIES_PREFERRED;
static float dot(float[] a, float[] b) {
FloatVector acc = FloatVector.zero(S); int i = 0;
for (; i < S.loopBound(a.length); i += S.length()) acc = FloatVector.fromArray(S, a, i).fma(FloatVector.fromArray(S, b, i), acc);
float sum = acc.reduceLanes(VectorOperators.ADD);
for (; i < a.length; i++) sum += a[i] * b[i];
return sum;
}
public static void main(String[] args) {
float[] a = new float[1003], b = new float[1003]; float expect = 0;
for (int i = 0; i < a.length; i++) { a[i] = i % 7; b[i] = 2; expect += a[i] * b[i]; }
System.out.println("dot=" + dot(a, b) + " scalar=" + expect);
System.out.println("species lanes (machine dependent): " + S.length());
}
}
Output from 10-vector.txt:
warning: [incubating] using incubating module(s): jdk.incubator.vector
1 warning
WARNING: Using incubator modules: jdk.incubator.vector
dot=6008.0 scalar=6008.0
species lanes (machine dependent): 16
The two numbers match. The lane count printed is machine dependent: it is the width of the preferred vector on the CPU that ran the demo.
Go deeper
The reason it is still an incubator after ten rounds is not instability of the code you write: it is that the API is waiting for Project Valhalla so vectors can be real value types. Until then, expect and treat the performance win as something you must measure on your own hardware.
- JEP page: JEP 508
- Vector API guide (JEP 537)
- Source and output: src/VectorDemo.java, output/10-vector.txt
Faster and smaller with no code change: the runtime and tooling JEPs
Seven of the JEPs change nothing you write but change what the JVM does. This section runs each one that can be observed. Compact object headers (JEP 519, product in 25) shrink the header that every object carries. The demo allocates a million objects holding twoints and divides the thread’s allocated bytes by the count, once without the flag and once with -XX:+UseCompactObjectHeaders. Source: HeaderSize.java, output 11-compact-headers.txt:
bytes per object (two ints): 24
UseCompactObjectHeaders: (not set)
bytes per object (two ints): 16
UseCompactObjectHeaders: -XX:+UseCompactObjectHeaders
-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational; the log line proves which mode started (source GcNamesDemo.java, output 12-shenandoah.txt):
$ java -XX:+UseShenandoahGC -Xlog:gc+init GcNamesDemo | grep Mode (25.0.5.1)
[info][gc,init] Mode: Snapshot-At-The-Beginning (SATB)
$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init GcNamesDemo | grep Mode (25.0.5.1)
[info][gc,init] Mode: Generational
Ahead-of-time cache ergonomics and method profiling (JEP 514 and JEP 515, final in 25) make the Project Leyden startup cache easy: one command runs the app and writes the cache, a second command uses it. The app is AotApp.java and the transcript is 13-aot-cache.txt:
$ java -XX:AOTCacheOutput=app.aot -cp app.jar AotApp (25.0.5.1)
1334 items, first 1 | 666 items, first 3 bb
Temporary AOTConfiguration recorded: app.aot.config
Launching child process java to assemble AOT cache app.aot using configuration app.aot.config
Picked up JAVA_TOOL_OPTIONS: -Djava.class.path=app.jar -XX:AOTCacheOutput=app.aot -XX:AOTConfiguration=app.aot.config -XX:AOTMode=create
Reading AOTConfiguration app.aot.config and writing AOTCache app.aot
AOTCache creation is complete: app.aot N bytes
Removed temporary AOT configuration file app.aot.config
startup, 5 runs each, wall milliseconds (indicative, machine dependent):
run 1: plain 88 ms with -XX:AOTCache 59 ms
run 2: plain 85 ms with -XX:AOTCache 70 ms
run 3: plain 107 ms with -XX:AOTCache 56 ms
run 4: plain 113 ms with -XX:AOTCache 76 ms
run 5: plain 108 ms with -XX:AOTCache 65 ms
In the five runs committed in the transcript the plain start took 85 to 113 ms and the start with the cache took 56 to 76 ms, so the cache was faster in 5 of 5 runs. Treat the numbers as indicative: this is a tiny program and a loaded shared machine, and the transcript says so in its own header.
JFR CPU-time profiling and method timing (JEP 509 experimental, JEP 520 final) are the profiling additions. CpuWork burns CPU in two named methods (CpuWork.java); 14-jfr.txt shows the samples landing on the hot one and the timing and trace events for the others:
$ java -XX:StartFlightRecording:filename=cpu.jfr,jdk.CPUTimeSample#enabled=true,jdk.CPUTimeSample#throttle=10ms CpuWork (25.0.5.1)
top frame of each jdk.CPUTimeSample event (counts vary run to run):
147 CpuWork.hot(int)
1 java.lang.Integer.numberOfTrailingZeros(int)
1 CpuWork.main(String[])
$ java -XX:StartFlightRecording:filename=mt.jfr,method-timing=CpuWork::hot,method-trace=CpuWork::cold CpuWork
method = CpuWork.hot(int)
invocations = 343
jdk.MethodTrace events for CpuWork.cold: 343
No example for two of the eighteen. JEP 503 removes the 32-bit x86 port, which is a platform change, and JEP 518 changes how JFR walks stacks (at safepoints, minimising safepoint bias), which has no visible API. Neither is runnable as a demo, so I describe them from the JEP text and do not claim to have tested them. The sample counts in the JFR transcript vary from run to run.
Go deeper: flags, defaults and what to check before you switch
Compact headers: it is an opt-in flag in 25, not the default, and it requires a restart. The saving depends on your object mix, so measure with your own heap histogram before and after. Generational Shenandoah: the default Shenandoah mode in the log above is “Snapshot-At-The-Beginning (SATB)”, so the generational mode is something you turn on deliberately. AOT cache: the cache is tied to the exact JDK build and the class path that created it, so build it in the same image that runs the app; the one-step -XX:AOTCacheOutput run launches a child JVM to assemble it, as the transcript shows. JFR: jdk.CPUTimeSample captured stacks in the run above on Linux, the platform the JEP targets; method timing and tracing are selected by method-timing= and method-trace= options on the recording.
The wider picture of what these save on a service, measured on JDK 25 with garbage collectors side by side, is in the repository’s gc-basics module and the compact-header chapter of the Java 27 post, which covers what changed in the next releases.
- JEP pages: JEP 519, JEP 521, JEP 514, JEP 515, JEP 509, JEP 518, JEP 520, JEP 503
- Sources: src/HeaderSize.java, src/AotApp.java, src/CpuWork.java
- Run everything: run.sh
Common mistakes, with the real compiler messages
Four compile failures worth recognising, from 15-compile-errors.txt (sources in the broken/ folder, which is not part of the normal build):$ javac --release 25 broken/PreviewWithoutFlag.java (25.0.5.1)
broken/PreviewWithoutFlag.java:5: error: primitive patterns are a preview feature and are disabled by default.
if (v instanceof int i) System.out.println(i);
^
(use --enable-preview to enable primitive patterns)
1 error
$ javac broken/ThisBeforeSuper.java (25.0.5.1)
broken/ThisBeforeSuper.java:8: error: cannot reference describe() before supertype constructor has been called
System.out.println(describe()); // instance method call before super(): rejected
^
1 error
$ javac broken/AmbiguousModuleImport.java (25.0.5.1)
broken/AmbiguousModuleImport.java:6: error: reference to Date is ambiguous
Date d = null; // which Date?
^
both class java.sql.Date in java.sql and class java.util.Date in java.util match
1 error
$ javac --release 25 --enable-preview broken/ShutdownOnFailure21Style.java (25.0.5.1)
broken/ShutdownOnFailure21Style.java:4: error: cannot find symbol
try (var s = new StructuredTaskScope.ShutdownOnFailure()) { var f = s.fork(() -> "x"); s.join(); System.out.println(f.get()); } } }
^
symbol: class ShutdownOnFailure
location: interface StructuredTaskScope
1 error
- Preview without the flag: add
--enable-preview --release 25(and the same--enable-previewwhen you run). - Instance call before
super(): move the call after it, or compute the value in the prologue without usingthis. - Ambiguous module import: add a single-type import for the name you mean.
- Java 21 structured-concurrency code: rewrite
ShutdownOnFailureandShutdownOnSuccessuses withStructuredTaskScope.open(...)and aJoiner.
Should you move from 21 to 25? For most services yes, because it is the current LTS and you stay on a supported line, but not for these features: the final ones that change your code (scoped values, flexible constructors, compact source files, module imports, KDF) are conveniences, and none of the four previews is something to build on in production. The reasons to move are support, the runtime flags above and the removals; plan the move with the upgrade guide, not with this page.
FAQ
Is Java 25 an LTS release?
Yes. The Oracle Java SE support roadmap lists it as the LTS after 21, and the JDK 25 project page gives 16 September 2025 as the GA date.
Which Java 25 features are final?
Scoped values (506), KDF API (510), module import declarations (511), compact source files and instance main (512), flexible constructor bodies (513), and the runtime changes 503, 514, 515, 518, 519, 520 and 521. The previews are 470, 502, 505 and 507, 508 is an incubator and 509 is experimental.
Do I need flags to run the examples?
Only for the preview and incubator ones: --release 25 --enable-preview to compile and --enable-preview to run for 470, 502, 505 and 507, and --add-modules jdk.incubator.vector for 508. ./run.sh in the repository passes the right flags for each.
Further reading
- The companion project: java25-features module (README, sources, committed output)
- Java 21 Features with Examples
- Java 21 to 25 Upgrade Guide (with AI Prompts)
- Java 27: every JEP, plus the Java 26 changes
- Key Derivation Function API (JEP 510)
- Structured Concurrency in Java
- JDK 25 project page
- Oracle JDK 25 release notes
The earlier Java 21 to 25 walkthrough (kept unchanged): records, pattern switch, virtual threads, sequenced collections, scoped values, structured concurrency and six AI prompts
Versions. JDK 21.0.12.1 (Amazon Corretto), 25.0.4.1 (Temurin, LTS), 26.0.2.1 and 27 (Corretto; Java 27 reached GA on 15 September 2026), and Corretto 23.0.2 and 24.0.2 from container images wherever the question was “which release changed this?”. Every code block below links to the file it came from in asmhatre/javademos and every output block to the transcript it was copied from. Corrected 21 September 2026: this page called structured concurrency final in Java 25 (it is the fifth preview), its example used a method that does not exist on 26 or 27, its FAQ listedThread.stopandObject.finalizeas removed in 25 (Thread.stopwent in 26;finalizestill runs), and its virtual-thread prompt still told the AI thatsynchronizedblocks pin carriers, which stopped being true in Java 24.
Which Java release is which?
Java ships a new release every six months, in March and September. Most of them are supported for only six months. Every second one is a long-term-support (LTS) release, and that is the one companies actually run in production: 8, 11, 17, 21 and 25 so far, with the next LTS planned for Java 29 in September 2027 (Oracle’s Java SE Support Roadmap, read on 2026-09-21). That is why this article compares 21 with 25 and treats 22 to 24 as the road between them.- What 26 and 27 changed, JEP by JEP, and what an LTS jump to 29 will inherit: Java 27 Is Out: Every JEP, Plus the Java 26 Changes You Skipped.
- The lane table from 25 to 29 with the support windows: chapter 12.
1. Records — Data Classes, Finally
A record is a class whose only job is to carry data. You list the fields once, in the header, and the compiler writes the constructor, the accessors,equals, hashCode and toString for you. Records are immutable by default, which makes them ideal for DTOs and value objects. The compact constructor is the place for validation: it runs before the fields are assigned, so you never repeat the assignments. The record below is exactly the compact form; without the compact constructor it is a one-line declaration. The code is in HubExamples.java.
public record Customer(Long id, String email, String country) {
public Customer {
Objects.requireNonNull(email, "email must not be null");
if (!email.contains("@")) throw new IllegalArgumentException("Invalid email");
}
}
This is what it printed on JDK 25 (the same lines print on 21, 26 and 27, see transcript 80):
CHECK ok : record accessor: c.email()
CHECK ok : record toString: Customer[id=1, [email protected], country=IN]
CHECK ok : compact constructor rejects an email without @: Invalid email
- Records work well as DTOs and projections. They cannot be JPA
@Entityclasses: JPA needs a no-arg constructor, mutable fields and a non-final class. The FAQ below has the details. - The language feature itself: JEP 395, Records.
2. Pattern Matching for Switch
Switch expressions can now destructure records and match by type, which eliminates mostinstanceof chains. Combined with a sealed interface (an interface that names every class allowed to implement it), the compiler enforces exhaustiveness: if you add a fourth shape and forget to handle it, the code stops compiling instead of failing at run time. A when clause, the guard, refines a match without nesting.
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
case Triangle(double b, double h) -> 0.5 * b * h;
};
}
static String classify(Shape s) {
return switch (s) {
case Circle c when c.r() > 100 -> "large circle";
case Circle c -> "small circle";
case Square sq -> "square";
case Triangle t -> "triangle";
};
Full source: HubExamples.java. Output on JDK 25, identical on the other three JDKs:
CHECK ok : area(Square(3)) == 9.0
CHECK ok : area(Triangle(4, 5)) == 10.0
CHECK ok : guard pattern: Circle(101) is a large circle
CHECK ok : guard pattern: Circle(1) is a small circle
- Primitive patterns, the next step, are still a preview in 27 (fifth preview): chapter 5.
- The language feature: JEP 441, Pattern Matching for switch.
3. Virtual Threads (Project Loom)
Virtual threads are cheap, JVM-managed threads backed by a small carrier-thread pool. You can spawn millions where platform threads would exhaust memory at a few thousand. The API is deliberately identical toThread, so there are no reactive callbacks to learn: you write the blocking code you always wrote and the JVM parks the virtual thread while it waits.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
return done.incrementAndGet();
}));
}
Thread vt = Thread.ofVirtual().name("my-vthread").start(() -> { });
vt.join();
Ten thousand tasks that each block for 100 ms would take a thousand seconds one after another. The run finishes in seconds (the exact figure depends on the machine, so the transcript asserts it rather than printing it). Source: HubExamples.java; output on JDK 25:
CHECK ok : all 10,000 virtual-thread tasks completed before close() returned
CHECK ok : and it took seconds, not the 1,000 s a serial loop needs (exact time is machine dependent, not printed)
CHECK ok : Thread.ofVirtual().name(..).start(..) gives a virtual thread
There is one caveat that changed while nobody was watching. A virtual thread is mounted on a carrier thread while it runs. If it blocks while it is holding a synchronized monitor, older JVMs could not unmount it, so the carrier was pinned for as long as the thread waited. That advice, “avoid synchronized around blocking calls”, is still repeated everywhere. It stopped being true in Java 24 (JEP 491). The test below gives a single carrier thread to four virtual threads that each sleep 200 ms inside a synchronized block: pinned, they queue up and take about 800 ms; unpinned, they overlap and take about 200 ms.
$ java -Djdk.virtualThreadScheduler.parallelism=1 -Djdk.virtualThreadScheduler.maxPoolSize=1 PinningDemo (JDK 23, Corretto image)
4 virtual threads, 1 carrier, sleep(200) inside synchronized: SERIALISED (pinned): about 4 x 200 ms
$ java -Djdk.virtualThreadScheduler.parallelism=1 -Djdk.virtualThreadScheduler.maxPoolSize=1 PinningDemo (JDK 24, Corretto image)
4 virtual threads, 1 carrier, sleep(200) inside synchronized: OVERLAPPED (not pinned): about 200 ms
The old rule of thumb is off by one release. The rule of thumb in older articles, including this site’s upgrade guide until today, was that carriers pin on synchronized “on Java 21 to 24”. The measurement says 21 to 23. Native frames on the stack (a JNI or foreign call that calls back into Java) can still pin a carrier, so the audit prompt below still asks about them.
- The benchmarks, and the reasons a virtual thread is not always faster: Virtual Threads vs Platform Threads: Benchmarks and Code.
- Why pinning mattered and how to see it: chapter 14, the pinning row.
- The language-level detail: JEP 444, Virtual Threads and JEP 491, Synchronize Virtual Threads without Pinning.
4. Sequenced Collections
Java 21 added a uniform API for collections that have a defined encounter order.getFirst(), getLast(), addFirst(), addLast() and reversed() now work consistently on List, LinkedHashSet and LinkedHashMap. The thing worth knowing is that reversed() returns a view, not a copy: change the list afterwards and the view changes with it.
List<String> names = new ArrayList<>(List.of("alex", "brian", "chris"));
String first = names.getFirst(); // alex
String last = names.getLast(); // chris
List<String> backwards = names.reversed(); // [chris, brian, alex]
String snapshot = backwards.toString(); // written down before the list changes
names.add("dana"); // reversed() is a view, so it sees this
LinkedHashSet<Integer> nums = new LinkedHashSet<>(List.of(3, 1, 4, 1, 5));
int firstNum = nums.getFirst(); // 3
int lastNum = nums.getLast(); // 5
Source: HubExamples.java. Output on JDK 25:
CHECK ok : List.getFirst() / getLast()
CHECK ok : List.reversed(): [chris, brian, alex]
CHECK ok : reversed() is a view, not a copy: it sees the element added afterwards
CHECK ok : LinkedHashSet.getFirst() == 3, getLast() == 5
- The API and the three new interfaces: JEP 431, Sequenced Collections.
5. Scoped Values (JEP 506, Final in Java 25)
Scoped values are an immutable, structured replacement forThreadLocal. They are safer (read-only in inner scopes), automatically cleaned up when the scope exits, and far cheaper on virtual threads, where a single request may hop across many of them. You bind a value for the duration of a lambda, and every method called from inside it, however deep, can read it without it being passed as a parameter.
static final ScopedValue<String> CURRENT_USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println("java.version = " + System.getProperty("java.version"));
ScopedValue.where(CURRENT_USER, "ankur").run(() -> {
Check.that(CURRENT_USER.get().equals("ankur"), "inside the scope: CURRENT_USER.get() == ankur");
callDeepMethod();
});
try {
CURRENT_USER.get();
Check.that(false, "outside the scope get() should throw");
} catch (NoSuchElementException expected) {
Check.that(true, "outside the scope: CURRENT_USER.get() throws NoSuchElementException");
}
}
static void callDeepMethod() {
Check.that(CURRENT_USER.get().equals("ankur"), "a method that was never passed the value still sees it");
}
This is one of the two features from this article that changed status between the releases it covers, so the transcript (transcript 81) shows both sides: JDK 21 refuses to compile the file without --enable-preview because ScopedValue is a preview API there, and JDK 25 (and 26 and 27) compiles and runs it with no flags. Source: ScopedValueDemo.java.
$ javac ScopedValueDemo.java (JDK 21, no flag)
<repo>/lanes/src/ScopedValueDemo.java:9: error: ScopedValue is a preview API and is disabled by default.
3 errors
exit=1
$ java ScopedValueDemo (JDK 25)
CHECK ok : inside the scope: CURRENT_USER.get() == ankur
CHECK ok : a method that was never passed the value still sees it
CHECK ok : outside the scope: CURRENT_USER.get() throws NoSuchElementException
- The 25, 26 and 27 runs side by side: transcript 81.
- Moving existing
ThreadLocalcode over is what the fifth prompt below is for. - The language-level detail: JEP 506, Scoped Values.
6. Structured Concurrency (JEP 505, Still a Preview in Java 25)
Structured concurrency treats a group of concurrent subtasks as a single unit of work. When the scope closes, every forked task that has not finished is cancelled. That removes the classic bug where one call fails and its siblings keep running in the background, unowned. It reads like a sequential call stack: you open a scope, fork, join, and the scope’s closing brace is the guarantee.static Dashboard fanOut(int userId) throws Exception {
try (var scope = StructuredTaskScope.open()) {
var user = scope.fork(() -> fetchUser(userId));
var order = scope.fork(() -> fetchOrder(userId));
scope.join();
return new Dashboard(user.get(), order.get());
}
}
static String firstSuccess() throws Exception {
try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> { Thread.sleep(200); return "slow"; });
scope.fork(() -> "fast");
return scope.join();
}
}
The code runs on Java 25, but only with --enable-preview. Without it javac refuses every mention of StructuredTaskScope, exactly as it refused ScopedValue on 21. JEP 505 in Java 25 is the fifth preview, the sixth is JEP 525 in 26 and the seventh is JEP 533 in 27. Source: StructuredHub.java; transcript: transcript 82.
$ javac StructuredHub.java (JDK 25, no flag)
<repo>/lanes/src/StructuredHub.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
5 errors
exit=1
$ java --enable-preview StructuredHub (JDK 25)
CHECK ok : fan-out: both results joined: Dashboard[user=user-7, order=order-for-7]
CHECK ok : anySuccessfulResultOrThrow(): the first result wins and the slow subtask is cancelled
Preview APIs are not stable APIs. A preview feature can change or vanish in the next release, and this one did. The factory method the code above calls,The rename is visible in the JDK itself. This isJoiner.anySuccessfulResultOrThrow(), was renamed toanySuccessfulOrThrow()in Java 26, and in 27Joinergained a third type parameter for the exceptionjoin()throws. If you useStructuredTaskScopein a build that targets 25, keep--enable-previewand expect to touch the code again.
javap on the Joiner class of each release (transcript 89), reduced to the one method, followed by the same example compiled on 26 with its old name and then run under its new one:
== JDK 25
public static <T> StructuredTaskScope$Joiner<T, T> anySuccessfulResultOrThrow();
== JDK 26
public static <T> StructuredTaskScope$Joiner<T, T> anySuccessfulOrThrow();
== JDK 27
public static <T, R_X extends Throwable> StructuredTaskScope$Joiner<T, T, R_X> anySuccessfulOrThrow(Function<Throwable, R_X>);
public static <T> StructuredTaskScope$Joiner<T, T, ExecutionException> anySuccessfulOrThrow();
$ javac --enable-preview --release 26 StructuredHub.java (JDK 26)
symbol: method <String>anySuccessfulResultOrThrow()
exit=1
$ java --enable-preview StructuredHubNew (JDK 26)
CHECK ok : anySuccessfulOrThrow(): the first result wins
The corrected example, StructuredHubNew.java, changes only that one identifier:
static String firstSuccess() throws Exception {
try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<String>anySuccessfulOrThrow())) {
scope.fork(() -> { Thread.sleep(200); return "slow"; });
scope.fork(() -> "fast");
return scope.join();
}
}
- How the API is shaped in 27, with a run of every joiner: chapter 7 and Java 27 Is Out: Every JEP, Plus the Java 26 Changes You Skipped.
- A longer treatment of scopes, joiners and cancellation: Structured Concurrency in Java.
- The proposals: JEP 505, JEP 525 and JEP 533.
What Java 26 and 27 change for the six features
You do not have to run a non-LTS release to know what a jump from 25 to 29 will look like, because 26 and 27 are the two rehearsals. The table takes the six features above, and the other things from the 21 to 25 list that moved, and says what each release does. Every cell is a run: chapter 14 maps each row to its transcript.| Thing | Java 25 (LTS) | Java 26 | Java 27 |
|---|---|---|---|
| Records, pattern switch, sequenced collections, virtual threads | final | same code, same result | same code, same result (80) |
| Scoped values | final (JEP 506) | unchanged | unchanged |
| Structured concurrency | fifth preview; needs --enable-preview | sixth preview; anySuccessfulOrThrow(); allSuccessfulOrThrow() returns a List | seventh preview; Joiner has three type parameters |
Virtual threads inside synchronized | not pinned | not pinned | not pinned |
Reflection writing to a final field | silent | warns (JEP 500) | warns (same run on 27: 91) |
Thread.stop() | throws UnsupportedOperationException | removed | removed |
-XX:-ZGenerational | ignored, with a warning | rejected: unrecognized option | rejected: unrecognized option |
| Default collector in a 1-CPU container | not measured here | Serial | G1 (JEP 523) |
| Size of an object with two ints | not measured here | 24 bytes | 16 bytes (JEP 534, compact headers) |
Should you stop at 25? For most teams, yes, and skip the non-LTS releases until 29. The exceptions are teams that want the 27 changes early, such as G1 as the default and compact object headers, and teams that need a security or performance fix that will not be backported. Whatever you choose, run your test suite on the newest release from time to time: the surprises are cheaper to find in the two-year run-up than in the last month before an LTS switch.
- The full 25 to 27 upgrade checklist, ordered by what stops a service from starting: chapter 13.
- Every JEP of 26 and 27, run: Java 27 Is Out: Every JEP, Plus the Java 26 Changes You Skipped.
- The step-by-step migration of a build, with the dependency versions that matter: Java 21 to Java 25 Upgrade Guide (with AI Prompts).
How the Code Works
- Records generate a canonical constructor and public accessor methods at compile time. The compact constructor form lets you add validation without repeating the field assignments.
- Pattern matching deconstructs a sealed hierarchy exhaustively: the compiler rejects the switch if any permitted subtype is missing. Guard clauses (
when) let you add fine-grained conditions without nesting. - Virtual threads are mounted onto a small pool of carrier threads. When a virtual thread calls a blocking operation (
sleep, a socket read, a JDBC call), it is unmounted from its carrier so the carrier can run another virtual thread. The virtual thread resumes on any available carrier when the blocking call returns. Since Java 24 that also holds inside asynchronizedblock. - Sequenced collections unify first/last access across all ordered JDK types through three new interfaces:
SequencedCollection,SequencedSet, andSequencedMap. - Scoped values bind data to a dynamic scope (a call tree) rather than a thread, so they propagate naturally across the fork boundaries of structured concurrency.
- Structured concurrency enforces a strict ownership relationship: the scope that forked a task is responsible for its lifetime. This makes concurrent code auditable the same way a sequential call stack is. It is still a preview API.
AI Prompts You Can Use
Copy these into Claude or ChatGPT and attach your file to apply each feature to your own code. Each prompt is also a file in the repository, so you can copy it from there or diff it against a newer version.Prompt 1 — Convert POJOs to Records
What it does: Reviews a Java class and converts it to a record if it is a pure data carrier. Moves constructor validation into a compact constructor. Flags classes that cannot be converted (mutable state, inheritance, JPA@Entity) and explains the reason for each.
When to use it: During a modernization pass on DTO, request/response, and value-object classes. File: lanes/prompts/features-1-records.txt.
Review the attached Java class and convert it to a Java 21 record if it is a pure data carrier. Preserve all validation from the old constructor inside a compact constructor. Flag fields that prevent conversion (e.g. mutable state, inheritance) and explain why.
Prompt 2 — Modernize instanceof Chains
What it does: Rewrites everyif (x instanceof Type) { Type t = (Type) x; ... } pattern to pattern matching. Introduces a sealed interface if the types form a closed hierarchy. Ensures the resulting switch is exhaustive.
When to use it: Any file with long if-instanceof chains, visitor implementations, or type-dispatch logic. File: lanes/prompts/features-2-pattern-switch.txt.
Refactor this Java code to use Java 21 pattern matching for switch. Introduce a sealed interface if the types form a closed hierarchy. Ensure the switch is exhaustive and remove all redundant casts and intermediate variables.
Prompt 3 — Migrate to Virtual Threads
What it does: Finds everyExecutors.newFixedThreadPool and newCachedThreadPool in a project and replaces them with newVirtualThreadPerTaskExecutor() where the tasks are I/O-bound. Lists cases where platform threads should be kept and justifies each retention.
When to use it: When starting a migration to virtual threads: get the full picture before changing any code. The prompt now knows that synchronized only pins on 21 to 23. File: lanes/prompts/features-3-virtual-threads.txt.
Find every usage of Executors.newFixedThreadPool and Executors.newCachedThreadPool in this project. Replace with Executors.newVirtualThreadPerTaskExecutor() where the tasks are I/O-bound. List any cases where platform threads should be kept (CPU-bound work, native frames on the stack, and on Java 21 to 23 also synchronized blocks that block, which pin the carrier thread until Java 24) and justify each decision.
Prompt 4 — Adopt Sequenced Collections
What it does: Replaces verbose first/last access patterns (list.get(0), list.get(list.size()-1), Collections.reverse(list)) with the new Java 21 sequenced API. Keeps behaviour identical.
When to use it: Part of a Java 21+ modernization pass: quick wins in readability with zero behavioural risk. File: lanes/prompts/features-4-sequenced-collections.txt.
Rewrite this code to use Java 21 sequenced collection APIs (getFirst, getLast, reversed) instead of list.get(0), list.get(list.size()-1), and manual reversal. Keep behaviour identical.
Prompt 5 — Replace ThreadLocal with ScopedValue
What it does: IdentifiesThreadLocal usages in a file and proposes a migration to ScopedValue (final in Java 25). Shows before/after code and explains why ScopedValue is safer under virtual threads and structured concurrency.
When to use it: After migrating to virtual threads, when you need to pass request-scoped data (user ID, trace ID, tenant) without threading it through every method signature. File: lanes/prompts/features-5-scoped-values.txt.
Identify ThreadLocal usages in this file. Propose a migration to Java 25 ScopedValue, showing before/after code and explaining why ScopedValue is safer under virtual threads and structured concurrency.
Prompt 6 — Structured Concurrency Refactor
What it does: Converts aCompletableFuture.allOf fan-out pipeline to a StructuredTaskScope. Explains how error propagation and automatic cancellation differ from the CompletableFuture approach. It now tells the model that the API is a preview and that the factory-method names differ between 25 and 26.
When to use it: When you have parallel fan-out logic that needs proper cancellation on failure, a common pattern in microservice aggregators, and you accept a preview API. File: lanes/prompts/features-6-structured-concurrency.txt.
Refactor this CompletableFuture.allOf pipeline to use StructuredTaskScope. Note that StructuredTaskScope is still a preview API in Java 25, 26 and 27, so the build needs --enable-preview and the code must use the factory-method names of the JDK it targets (Joiner.anySuccessfulResultOrThrow() on 25, anySuccessfulOrThrow() on 26 and 27). Preserve error propagation semantics and show what happens on cancellation. Explain the difference from the original CompletableFuture approach.
See Also
- Virtual Threads vs Platform Threads — Benchmarks and Code
- Java Streams API Deep Dive + Collectors Cookbook
- Java Concurrency Deep Dive: CompletableFuture, ExecutorService, ForkJoinPool
- Modern Java Testing: JUnit 6 + AssertJ + Mockito 5 + Testcontainers
- Java 21 to Java 25 Upgrade Guide (with AI Prompts)
- AI Prompts Playbook: Upgrading Java 8 → 11 → 17 → 21 → 25
- Demystifying Thread Safety in Java: A Practical Guide
- From Raw Threads to Virtual Threads: A Developer’s Guide
- Java Memory Management and Garbage Collection: Deep Dive
- Overview of New Features in Java 19
- Java 27 Is Out: Every JEP, Plus the Java 26 Changes You Skipped
- Java Vector API (JEP 537): a SIMD guide
- Structured Concurrency in Java
FAQs
Is Java 25 backward compatible with Java 21?
Yes for almost all application code. The changes that bite are these, each checked on a JDK: you can no longer install a Security Manager (System.setSecurityManager throws on 25, and already did on 21 by default); Thread.suspend and resume still compile on 21 and do not on 23 or later; Thread.stop compiles on 25 but throws, and is gone in 26; Object.finalize still runs unless you pass --finalization=disabled; and sun.misc.Unsafe memory methods and JNI loading print run-time warnings from Java 24. There is also the migration from javax.* to jakarta.* if you have not done it for Java EE dependencies. Transcripts: 83, 84, 85, 86.
Do virtual threads replace reactive frameworks?
For most I/O-bound services, yes: you can write straight-line blocking code and get throughput comparable to reactive approaches. Reactive still has advantages for backpressure-heavy streaming pipelines (processing millions of events with fine-grained flow control) or when you need the functional composition style of Project Reactor or RxJava.Can I use records with JPA/Hibernate?
Records work well as DTOs and projections (read-only query results). They cannot be JPA@Entity classes because JPA requires a no-arg constructor, mutable fields, and non-final classes. See the Hibernate Tutorials series for projection patterns.
Is structured concurrency safe to use in production on 25?
It runs, but it is a preview API: your build needs--enable-preview, your class files are tied to that exact release, and the API has already changed twice between 25 and 27. Use it in code you are willing to touch again, and prefer a plain ExecutorService with virtual threads where the cancellation guarantee is not essential.
Conclusion
Java 25 LTS is where Loom and Amber land their finished pieces: records, pattern matching, virtual threads and scoped values change how you model data and run code, and the synchronized-pinning problem that made early adopters nervous is gone. Structured concurrency is the piece that has not landed yet, and it is still moving. Together they make idiomatic Java read closer to Kotlin or Scala without sacrificing the ecosystem. The six prompts above give you a practical route to applying each feature to an existing codebase today.Further Reading
- asmhatre/javademos: the code and transcripts behind this article, and the chapters that go deeper (chapter 14 checks every claim).
- JEP 444 — Virtual Threads (final in Java 21)
- JEP 441 — Pattern Matching for switch (final in Java 21)
- JEP 431 — Sequenced Collections (final in Java 21)
- JEP 491 — Synchronize Virtual Threads without Pinning (final in Java 24)
- JEP 505 — Structured Concurrency (fifth preview in Java 25)
- JEP 506 — Scoped Values (final in Java 25)
- OpenJDK — JDK 25 Release Overview
- Oracle’s Java SE Support Roadmap
No Comments yet!