Add java25-features module: the 18 JEPs of JDK 25 with runnable demos, captured output and compile-error cases

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5uFE41EgmSXEP4axJ
This commit is contained in:
asmhatre
2026-11-25 13:20:40 +05:30
co-authored by Claude Sonnet 5.5
parent 876ae1bb5c
commit 1fb1455734
36 changed files with 459 additions and 1 deletions
+13
View File
@@ -0,0 +1,13 @@
# java25-features — Java 25 features with examples
Companion code for the ankurm.com article **Java 25 Features with Examples** (https://ankurm.com/java-21-to-25-lts-features/). The explanation lives in the article; this folder holds the runnable sources and the transcripts they produced. There is no `docs/` folder: the depth is inside the article itself, in its expandable sections.
```bash
JDK25=/path/to/jdk25 ./run.sh # regenerates output/*.txt
```
- `src/` compiles and runs unchanged on the JDK named in each output header (preview demos need `--enable-preview`, the Vector API needs `--add-modules jdk.incubator.vector`; `run.sh` passes both).
- `broken/` fails to compile on purpose; the compiler's own message is committed in `output/15-compile-errors.txt`.
- `output/` is real captured output, regenerated by `run.sh`. Timings (the AOT startup runs, the JFR sample counts) are machine dependent: shape, not results.
Tested on: Eclipse Temurin 25.0.5.1+2 (JDK 25 GA was 2025-09-16).
@@ -0,0 +1,9 @@
import module java.base;
import module java.sql; // java.sql exports java.sql.Date, java.base exports java.util.Date
public class AmbiguousModuleImport {
public static void main(String[] args) {
Date d = null; // which Date?
System.out.println(d);
}
}
@@ -0,0 +1,7 @@
// JEP 507 is a preview in 25: compiling without --enable-preview must fail.
public class PreviewWithoutFlag {
public static void main(String[] args) {
long v = 42L;
if (v instanceof int i) System.out.println(i);
}
}
@@ -0,0 +1,4 @@
// The Java 21 preview shape (ShutdownOnFailure) does not exist in 25: this must fail to compile.
import java.util.concurrent.StructuredTaskScope;
public class ShutdownOnFailure21Style { public static void main(String[] a) throws Exception {
try (var s = new StructuredTaskScope.ShutdownOnFailure()) { var f = s.fork(() -> "x"); s.join(); System.out.println(f.get()); } } }
@@ -0,0 +1,12 @@
// JEP 513 allows statements before super(), but not anything that reads `this`.
public class ThisBeforeSuper {
static class Base { Base() {} }
static class Child extends Base {
int side = 4;
String describe() { return "child"; }
Child() {
System.out.println(describe()); // instance method call before super(): rejected
super();
}
}
}
@@ -0,0 +1,7 @@
$ javac src/ScopedValuesDemo.java && java ScopedValuesDemo (25.0.5.1)
before by nobody
delete account by alice
nested rebind by admin
after nested by alice
after by nobody
call returned for bob
@@ -0,0 +1,3 @@
$ javac src/ModuleImportDemo.java && java ModuleImportDemo (25.0.5.1)
{4=[beta], 5=[alpha, gamma, delta]}
/tmp/x.txt 2025-09-16
@@ -0,0 +1,3 @@
$ java src/Hello.java (25.0.5.1)
Hello, Java 25
class name the launcher gave me: Hello
@@ -0,0 +1,4 @@
$ javac src/FlexibleConstructorDemo.java && java FlexibleConstructorDemo (25.0.5.1)
square side=4
old square side=0
rejected: side must be positive, got -1
+4
View File
@@ -0,0 +1,4 @@
$ javac src/KdfDemo.java && java KdfDemo (25.0.5.1)
OKM 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
RFC 5869 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
match true
@@ -0,0 +1,6 @@
$ javac --release 25 --enable-preview src/PrimitivePatternsPreview.java && java --enable-preview PrimitivePatternsPreview (25.0.5.1)
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
@@ -0,0 +1,9 @@
$ javac --release 25 --enable-preview src/StableValuesPreview.java && java --enable-preview StableValuesPreview (25.0.5.1)
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
@@ -0,0 +1,4 @@
$ javac --release 25 --enable-preview src/StructuredConcurrencyPreview.java && java --enable-preview StructuredConcurrencyPreview (25.0.5.1)
user after 50ms | orders after 80ms
winner: fast mirror after 30ms
join threw FailedException caused by java.lang.IllegalStateException: boom
+7
View File
@@ -0,0 +1,7 @@
$ javac --release 25 --enable-preview src/PemPreview.java && java --enable-preview PemPreview (25.0.5.1)
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAKBmGVhQYHIYYS9a5T+AJ8IcxKzPBdjXHOrHxoNCp0EQ=
-----END PUBLIC KEY-----
round trip equal: true
private key header: -----BEGIN PRIVATE KEY-----
+6
View File
@@ -0,0 +1,6 @@
$ javac --add-modules jdk.incubator.vector src/VectorDemo.java && java --add-modules jdk.incubator.vector VectorDemo (25.0.5.1)
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
@@ -0,0 +1,7 @@
$ javac src/HeaderSize.java && java HeaderSize (25.0.5.1)
bytes per object (two ints): 24
UseCompactObjectHeaders: (not set)
$ javac src/HeaderSize.java && java -XX:+UseCompactObjectHeaders HeaderSize (25.0.5.1)
bytes per object (two ints): 16
UseCompactObjectHeaders: -XX:+UseCompactObjectHeaders
+6
View File
@@ -0,0 +1,6 @@
$ 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
+15
View File
@@ -0,0 +1,15 @@
$ 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
+10
View File
@@ -0,0 +1,10 @@
$ 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
@@ -0,0 +1,27 @@
$ 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
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Java 25 features: every demo compiled and run on a real JDK 25; regenerates output/*.txt
# JDK25=/path/to/jdk25 ./run.sh
set -uo pipefail
unset JAVA_TOOL_OPTIONS _JAVA_OPTIONS
HERE="$(cd "$(dirname "$0")" && pwd)"
JDK25="${JDK25:-/opt/jdks/jdk25}"
J="$JDK25/bin"
OUT="$HERE/output"; mkdir -p "$OUT"; B="$(mktemp -d)"; trap 'rm -rf "$B"' EXIT
cd "$HERE"
ver() { "$J/java" -version 2>&1 | sed -n 1p | sed 's/.*"\(.*\)".*/\1/'; }
# cr FILE CLASS [javac flags...] -- [java flags...]
cr() { local src="$1" cls="$2"; shift 2; local jf=() rf=(); while [ $# -gt 0 ] && [ "$1" != "--" ]; do jf+=("$1"); shift; done; [ "${1:-}" = "--" ] && shift; rf=("$@")
local o; o="$(mktemp -d -p "$B")"
echo "\$ javac ${jf[*]:-} $src && java ${rf[*]:-} $cls ($(ver))"
"$J/javac" "${jf[@]}" -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v -e '^Note:' ; "$J/java" "${rf[@]}" -cp "$o" "$cls" 2>&1 | grep -v -e '^Picked up'; }
co() { local src="$1"; shift; local o; o="$(mktemp -d -p "$B")"
echo "\$ javac $* $src ($(ver))"; local r; r="$("$J/javac" "$@" -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v -e '^Note:')"; if [ -n "$r" ]; then echo "$r"; else echo "(compiled cleanly)"; fi; }
PV=(--release 25 --enable-preview)
cr src/ScopedValuesDemo.java ScopedValuesDemo > "$OUT/01-scoped-values.txt"
cr src/ModuleImportDemo.java ModuleImportDemo > "$OUT/02-module-import.txt"
{ echo "\$ java src/Hello.java ($(ver))"; "$J/java" src/Hello.java 2>&1; } > "$OUT/03-compact-source.txt"
cr src/FlexibleConstructorDemo.java FlexibleConstructorDemo > "$OUT/04-flexible-constructor.txt"
cr src/KdfDemo.java KdfDemo > "$OUT/05-kdf.txt"
cr src/PrimitivePatternsPreview.java PrimitivePatternsPreview "${PV[@]}" -- --enable-preview > "$OUT/06-primitive-patterns.txt"
cr src/StableValuesPreview.java StableValuesPreview "${PV[@]}" -- --enable-preview > "$OUT/07-stable-values.txt"
cr src/StructuredConcurrencyPreview.java StructuredConcurrencyPreview "${PV[@]}" -- --enable-preview > "$OUT/08-structured-concurrency.txt"
cr src/PemPreview.java PemPreview "${PV[@]}" -- --enable-preview > "$OUT/09-pem.txt"
cr src/VectorDemo.java VectorDemo --add-modules jdk.incubator.vector -- --add-modules jdk.incubator.vector > "$OUT/10-vector.txt"
# 519 compact object headers: bytes per two-int object, flag off and on
{ cr src/HeaderSize.java HeaderSize; echo; cr src/HeaderSize.java HeaderSize -- -XX:+UseCompactObjectHeaders; } > "$OUT/11-compact-headers.txt"
# 521 generational Shenandoah
{ for f in "-XX:+UseShenandoahGC" "-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational"; do
echo "\$ java $f -Xlog:gc+init GcNamesDemo | grep Mode ($(ver))"
o="$(mktemp -d -p "$B")"; "$J/javac" -d "$o" src/GcNamesDemo.java; "$J/java" $f -Xlog:gc+init -cp "$o" GcNamesDemo 2>&1 | grep -e 'Mode:' | sed 's/^\[[^]]*\]//'; echo; done; } > "$OUT/12-shenandoah.txt"
# 514 and 515 AOT cache: one command creates it, a second run uses it
{ A="$(mktemp -d -p "$B")"; "$J/javac" -d "$A" src/AotApp.java; ( cd "$A" && "$J/jar" cf app.jar AotApp*.class )
echo "\$ java -XX:AOTCacheOutput=app.aot -cp app.jar AotApp ($(ver))"; ( cd "$A" && "$J/java" -XX:AOTCacheOutput=app.aot -cp app.jar AotApp 2>&1 | sed 's/ [0-9]* bytes/ N bytes/; s#/[^ ]*/bin/java#java#' )
echo; echo "startup, 5 runs each, wall milliseconds (indicative, machine dependent):"
t() { local s e; s=$(date +%s%N); ( cd "$A" && "$J/java" "$@" -cp app.jar AotApp >/dev/null 2>&1 ); e=$(date +%s%N); echo $(( (e - s) / 1000000 )); }
for i in 1 2 3 4 5; do p=$(t); a=$(t -XX:AOTCache=app.aot); echo "run $i: plain ${p} ms with -XX:AOTCache ${a} ms"; done; } > "$OUT/13-aot-cache.txt"
# 509 and 520 JFR
{ C="$(mktemp -d -p "$B")"; "$J/javac" -d "$C" src/CpuWork.java
echo "\$ java -XX:StartFlightRecording:filename=cpu.jfr,jdk.CPUTimeSample#enabled=true,jdk.CPUTimeSample#throttle=10ms CpuWork ($(ver))"
( cd "$C" && "$J/java" -XX:StartFlightRecording:filename=cpu.jfr,jdk.CPUTimeSample#enabled=true,jdk.CPUTimeSample#throttle=10ms -cp . CpuWork >/dev/null 2>&1
echo "top frame of each jdk.CPUTimeSample event (counts vary run to run):"
"$J/jfr" print --events jdk.CPUTimeSample --stack-depth 1 cpu.jfr | grep -A1 'stackTrace = \[' | grep -v -e 'stackTrace' -e '^--' | sed 's/ line:.*//; s/^ *//' | sort | uniq -c | sort -rn
echo; echo "\$ java -XX:StartFlightRecording:filename=mt.jfr,method-timing=CpuWork::hot,method-trace=CpuWork::cold CpuWork"
"$J/java" -XX:StartFlightRecording:filename=mt.jfr,method-timing=CpuWork::hot,method-trace=CpuWork::cold -cp . CpuWork >/dev/null 2>&1
"$J/jfr" print --events jdk.MethodTiming mt.jfr | sed -n '/method =/p;/invocations/p'
echo "jdk.MethodTrace events for CpuWork.cold: $("$J/jfr" print --events jdk.MethodTrace mt.jfr | grep -c 'method = CpuWork.cold')" ); } > "$OUT/14-jfr.txt"
{ co broken/PreviewWithoutFlag.java --release 25; echo; co broken/ThisBeforeSuper.java; echo; co broken/AmbiguousModuleImport.java; echo; co broken/ShutdownOnFailure21Style.java "${PV[@]}"; } > "$OUT/15-compile-errors.txt"
exit 0
+13
View File
@@ -0,0 +1,13 @@
import java.util.*;
import java.util.stream.*;
/** JEP 514 and 515: a small app that loads many JDK classes (streams, lambdas, formatting) so an AOT cache has something to cache. */
public class AotApp {
public static void main(String[] args) {
long t0 = System.nanoTime();
Map<Boolean, List<Integer>> parts = IntStream.rangeClosed(1, 2000).boxed().collect(Collectors.partitioningBy(i -> i % 3 == 0));
String s = parts.values().stream().map(l -> String.format("%d items, first %s", l.size(), l.get(0))).collect(Collectors.joining(" | "));
Optional<String> o = Stream.of("a", "bb", "ccc").filter(x -> x.length() > 1).findFirst();
System.out.println(s + " " + o.orElse("-"));
}
}
+10
View File
@@ -0,0 +1,10 @@
/** Burns CPU in two named methods so the JFR demos (509, 520) have something to sample and time. */
public class CpuWork {
static long hot(int n) { long x = 0; for (int i = 0; i < n; i++) x += Long.numberOfTrailingZeros(i * 31L + x); return x; }
static long cold(int n) { long x = 0; for (int i = 0; i < n; i++) x ^= i; return x; }
public static void main(String[] args) {
long end = System.nanoTime() + 1_500_000_000L, sink = 0;
while (System.nanoTime() < end) { sink += hot(2_000_000); sink += cold(10_000); }
System.out.println("done " + (sink != 42));
}
}
@@ -0,0 +1,27 @@
/** 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()); }
}
}
+8
View File
@@ -0,0 +1,8 @@
import java.lang.management.*;
/** JEP 521 (product in 25): which collector is running? */
public class GcNamesDemo {
public static void main(String[] args) {
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) System.out.println(b.getName());
}
}
+17
View File
@@ -0,0 +1,17 @@
import java.lang.management.ManagementFactory;
/** JEP 519 (product in 25): how many bytes does one small object cost? Measured from the thread's allocation counter. */
public class HeaderSize {
static final class P { int a, b; }
static Object[] keep = new Object[1_000_000];
public static void main(String[] args) {
var t = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long id = Thread.currentThread().threadId();
for (int i = 0; i < 1000; i++) keep[i] = new P(); // warm up
long before = t.getThreadAllocatedBytes(id);
for (int i = 0; i < keep.length; i++) keep[i] = new P();
long used = t.getThreadAllocatedBytes(id) - before;
System.out.println("bytes per object (two ints): " + used / keep.length);
System.out.println("UseCompactObjectHeaders: " + ManagementFactory.getRuntimeMXBean().getInputArguments().stream().filter(s -> s.contains("CompactObjectHeaders")).findFirst().orElse("(not set)"));
}
}
+7
View File
@@ -0,0 +1,7 @@
// 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());
}
+19
View File
@@ -0,0 +1,19 @@
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));
}
}
+11
View File
@@ -0,0 +1,11 @@
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));
}
}
+14
View File
@@ -0,0 +1,14 @@
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(""));
}
}
@@ -0,0 +1,24 @@
/** 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));
}
}
+21
View File
@@ -0,0 +1,21 @@
/** 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);
}
}
@@ -0,0 +1,23 @@
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());
}
}
@@ -0,0 +1,29 @@
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());
}
}
}
+19
View File
@@ -0,0 +1,19 @@
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());
}
}