From d4b8552957b00eac81132ae155d2e5cc25f2bb81 Mon Sep 17 00:00:00 2001 From: asmhatre Date: Thu, 3 Dec 2026 09:10:29 +0530 Subject: [PATCH] Add java28-features module: the JDK 28 JEP list so far, one example per JEP on 28-ea+26, behaviour changes against JDK 27 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b7N4ZDbUtA3ofqAqRV --- README.md | 1 + java28-features/README.md | 55 +++++++ java28-features/behaviour/Behaviour.java | 46 ++++++ java28-features/behaviour/RawConditional.java | 7 + java28-features/behaviour/SwitchGuard.java | 10 ++ java28-features/broken/EarlyConstruction.java | 9 ++ java28-features/broken/RecordThis.java | 13 ++ java28-features/output/00-environment.txt | 12 ++ java28-features/output/01-value-classes.txt | 14 ++ .../output/02-preview-changes-records.txt | 12 ++ java28-features/output/03-strict-fields.txt | 17 +++ java28-features/output/04-json.txt | 10 ++ .../output/05-structured-concurrency.txt | 9 ++ java28-features/output/06-pem.txt | 7 + java28-features/output/07-lazy-constants.txt | 7 + java28-features/output/08-vector.txt | 19 +++ java28-features/output/09-zgc.txt | 37 +++++ java28-features/output/10-shenandoah.txt | 4 + java28-features/output/11-aot-code.txt | 21 +++ java28-features/output/12-pkcs12-openssl.txt | 27 ++++ .../output/13-behaviour-changes.txt | 24 +++ java28-features/output/14-javac-changes.txt | 20 +++ java28-features/output/15-finals-on-jdk27.txt | 16 ++ java28-features/output/16-platform.txt | 2 + java28-features/run.sh | 137 ++++++++++++++++++ java28-features/src/AotApp.java | 19 +++ java28-features/src/Float16Demo.java | 7 + java28-features/src/HeapProbe.java | 10 ++ java28-features/src/IntegerEquality.java | 6 + java28-features/src/JsonDemo.java | 26 ++++ java28-features/src/LazyDemo.java | 27 ++++ java28-features/src/PemDemo.java | 22 +++ java28-features/src/PlatformCheck.java | 7 + java28-features/src/StrictFields.java | 23 +++ java28-features/src/StructuredDemo.java | 39 +++++ java28-features/src/ValueClassDemo.java | 24 +++ java28-features/src/VectorDemo.java | 21 +++ 37 files changed, 767 insertions(+) create mode 100644 java28-features/README.md create mode 100644 java28-features/behaviour/Behaviour.java create mode 100644 java28-features/behaviour/RawConditional.java create mode 100644 java28-features/behaviour/SwitchGuard.java create mode 100644 java28-features/broken/EarlyConstruction.java create mode 100644 java28-features/broken/RecordThis.java create mode 100644 java28-features/output/00-environment.txt create mode 100644 java28-features/output/01-value-classes.txt create mode 100644 java28-features/output/02-preview-changes-records.txt create mode 100644 java28-features/output/03-strict-fields.txt create mode 100644 java28-features/output/04-json.txt create mode 100644 java28-features/output/05-structured-concurrency.txt create mode 100644 java28-features/output/06-pem.txt create mode 100644 java28-features/output/07-lazy-constants.txt create mode 100644 java28-features/output/08-vector.txt create mode 100644 java28-features/output/09-zgc.txt create mode 100644 java28-features/output/10-shenandoah.txt create mode 100644 java28-features/output/11-aot-code.txt create mode 100644 java28-features/output/12-pkcs12-openssl.txt create mode 100644 java28-features/output/13-behaviour-changes.txt create mode 100644 java28-features/output/14-javac-changes.txt create mode 100644 java28-features/output/15-finals-on-jdk27.txt create mode 100644 java28-features/output/16-platform.txt create mode 100755 java28-features/run.sh create mode 100644 java28-features/src/AotApp.java create mode 100644 java28-features/src/Float16Demo.java create mode 100644 java28-features/src/HeapProbe.java create mode 100644 java28-features/src/IntegerEquality.java create mode 100644 java28-features/src/JsonDemo.java create mode 100644 java28-features/src/LazyDemo.java create mode 100644 java28-features/src/PemDemo.java create mode 100644 java28-features/src/PlatformCheck.java create mode 100644 java28-features/src/StrictFields.java create mode 100644 java28-features/src/StructuredDemo.java create mode 100644 java28-features/src/ValueClassDemo.java create mode 100644 java28-features/src/VectorDemo.java diff --git a/README.md b/README.md index ec6ff1c..260f181 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ These modules keep only sources, a `run.sh` and their transcripts (`output/`). T | [`unsafe-migration/`](unsafe-migration) | sun.misc.Unsafe Memory Access Is Going Away: Find and Fix It in Your Dependencies (JEP 471 / 498) | what `--sun-misc-unsafe-memory-access` allow/warn/debug/deny do on JDK 25 (and 21, 26, 27), `javac` removal warnings, jdeps and a bytecode scan of 17 real jars, Netty and Guava at run time, a CAS field to `VarHandle`, an off-heap array to `MemorySegment`, a before/after equivalence check | | [`jpms-basics/`](jpms-basics) | Java Modules (JPMS) for Working Developers: module-info, exports, opens and jdeps | five modules built with plain `javac`/`java` on JDK 25: `exports` vs `opens` and the exact `InaccessibleObjectException` text, why `requires transitive` exists, services and `jlink --bind-services` (5 modules vs 49), split packages, automatic modules, the class path as the unnamed module, `jdeps --check/--jdk-internals/--generate-module-info`, and `jlink` image sizes | | [`crac/`](crac) | Spring Boot with CRaC: Checkpoint/Restore Startup Compared with the JDK AOT Cache and a Native Image | one Spring Boot 4.2 service started on a plain JVM, with the JDK AOT cache, from a CRaC checkpoint (at start-up and after warm-up) and as a GraalVM native image, ten interleaved rounds each; the open-file `CheckpointOpenFileException` and its fix, stale environment values, secrets inside the checkpoint, the `warp` and CRIU engines, and a cold page-cache run | +| [`java28-features/`](java28-features) | Java 28 Features: The JDK 28 JEP List So Far (With Examples) | one example per JDK 28 JEP on EA build 26, the record rule that changes under `--enable-preview`, PKCS #12/OpenSSL, javac and library behaviour changes against JDK 27 | ## Captured output (`docs/output/`) diff --git a/java28-features/README.md b/java28-features/README.md new file mode 100644 index 0000000..0819ee3 --- /dev/null +++ b/java28-features/README.md @@ -0,0 +1,55 @@ +# java28-features + +Companion module for the ankurm.com article **Java 28 Features: The JDK 28 JEP List So Far (With Examples)**: +https://ankurm.com/java-28-features-jep-list/ + +One runnable example per JDK 28 JEP that can be run on Linux/x64, plus a set of non-JEP changes that can break an upgrade. + +**Snapshot, not a final list.** Built on 2026-12-03, the scheduled day of Rampdown Phase One. At that time +openjdk.org/projects/jdk/28 (last update 2026-12-01) still said "JEPs targeted to JDK 28, so far". GA is scheduled for 2027-03-09. + +## Verified with + +| Thing | Version | +|---|---| +| JDK 28 early access | `28-ea+26-2195` (jdk.java.net/28), SHA-256 `6f8e6ab917f233ae3a880a6b6cb8a68489fcbce4778f322682b590871304147d` | +| JDK 27 (comparison) | `27.0.1.1+4-22` (jdk.java.net/27) | +| Older keystore readers | JDK `25.0.5.1`, `21.0.13.1` | +| OpenSSL | 3.0.13 | +| Machine | Linux x86_64, 2 vCPU container | + +The sandbox sets `_JAVA_OPTIONS=-XX:+UnlockDiagnosticVMOptions -XX:DisableIntrinsic=_base64_encodeBlock,_base64_decodeBlock` +(and a proxy configuration in `JAVA_TOOL_OPTIONS`). Both were left in place; only their "Picked up ..." banner lines are removed from transcripts. + +## Run + + JDK27=/path/to/jdk-27 JDK28=/path/to/jdk-28-ea ./run.sh + # optional: JDK25=... JDK21=... adds the older-keytool check + +## Files and transcripts + +| Topic | Source | Transcript | +|---|---|---| +| environment | `run.sh` | `output/00-environment.txt` | +| JEP 401 value objects | `src/ValueClassDemo.java`, `src/IntegerEquality.java` | `output/01-value-classes.txt` | +| JEP 401 record rule under preview | `broken/RecordThis.java` | `output/02-preview-changes-records.txt` | +| JEP 539 strict field initialization | `src/StrictFields.java`, `broken/EarlyConstruction.java` | `output/03-strict-fields.txt` | +| JEP 540 JSON (incubator) | `src/JsonDemo.java` | `output/04-json.txt` | +| JEP 543 structured concurrency | `src/StructuredDemo.java` | `output/05-structured-concurrency.txt` | +| JEP 542 PEM | `src/PemDemo.java` | `output/06-pem.txt` | +| JEP 547 lazy constants (4th preview) | `src/LazyDemo.java` | `output/07-lazy-constants.txt` | +| JEP 548 Vector API (13th incubator) | `src/VectorDemo.java`, `src/Float16Demo.java` | `output/08-vector.txt` | +| JEP 545 / 546 ZGC | `src/HeapProbe.java` | `output/09-zgc.txt` | +| JEP 535 Shenandoah | none: this JDK build does not include Shenandoah | `output/10-shenandoah.txt` | +| JEP 544 AOT code | `src/AotApp.java` | `output/11-aot-code.txt` | +| PKCS #12 default MAC | `run.sh` | `output/12-pkcs12-openssl.txt` | +| other behaviour changes | `behaviour/Behaviour.java` | `output/13-behaviour-changes.txt` | +| javac changes | `behaviour/RawConditional.java`, `behaviour/SwitchGuard.java` | `output/14-javac-changes.txt` | +| the two finalised APIs on JDK 27 | `src/StructuredDemo.java`, `src/PemDemo.java` | `output/15-finals-on-jdk27.txt` | +| JEP 541 macOS/x64 | `src/PlatformCheck.java` (the port itself was not built) | `output/16-platform.txt` | + +## Not verified here + +- Generational Shenandoah (JEP 535) was not run. +- macOS/x64 `configure` (JEP 541) was not run; the check was read in `make/autoconf/platform.m4` at tag `jdk-28+26`. +- The AOT timings are from a small program on a shared 2 vCPU machine and are noisy (see the min-max ranges). diff --git a/java28-features/behaviour/Behaviour.java b/java28-features/behaviour/Behaviour.java new file mode 100644 index 0000000..dbbfc2c --- /dev/null +++ b/java28-features/behaviour/Behaviour.java @@ -0,0 +1,46 @@ +// Non-JEP changes from the JDK 28 release notes. Run the same file on JDK 27 and JDK 28. +import java.lang.foreign.Linker; +import java.lang.foreign.ValueLayout; +import java.security.Security; +import java.text.ListFormat; +import java.util.List; +import javax.crypto.Cipher; +import java.security.KeyPairGenerator; + +public class Behaviour { + static class NotSerializable {} + + public static void main(String[] args) throws Exception { + System.out.println("-- ListFormat with single quotes in a custom pattern"); + try { + var f = ListFormat.getInstance(new String[] {"{0}, {1}", "{0}, {1}", "{0} and {1}", " '{0}', {1} ", ""}); + System.out.println("[" + f.format(List.of("bar", "foo")) + "]"); + } catch (Exception e) { + System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + + System.out.println("-- RSA/ECB/PKCS1Padding"); + var kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(2048); + var cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, kpg.generateKeyPair().getPublic()); + System.out.println("cipher initialised"); + + System.out.println("-- canonical size_t layout"); + var sizeT = Linker.nativeLinker().canonicalLayouts().get("size_t"); + System.out.println(sizeT + " equals JAVA_LONG: " + sizeT.equals(ValueLayout.JAVA_LONG)); + + System.out.println("-- ReflectionFactory on a non-serializable class"); + var factoryClass = Class.forName("sun.reflect.ReflectionFactory"); + Object factory = factoryClass.getMethod("getReflectionFactory").invoke(null); + var one = factoryClass.getMethod("newConstructorForSerialization", Class.class); + System.out.println("one-arg : " + one.invoke(factory, NotSerializable.class)); + var two = factoryClass.getMethod("newConstructorForSerialization", Class.class, java.lang.reflect.Constructor.class); + try { + Object c = two.invoke(factory, NotSerializable.class, Object.class.getDeclaredConstructor()); + System.out.println("two-arg : returned a constructor"); + } catch (java.lang.reflect.InvocationTargetException e) { + System.out.println("two-arg : " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage()); + } + } +} diff --git a/java28-features/behaviour/RawConditional.java b/java28-features/behaviour/RawConditional.java new file mode 100644 index 0000000..3e58f26 --- /dev/null +++ b/java28-features/behaviour/RawConditional.java @@ -0,0 +1,7 @@ +import java.util.List; + +class RawConditional { + Integer first(boolean b, List raw, List parameterized) { + return (b ? parameterized : raw).get(0); + } +} diff --git a/java28-features/behaviour/SwitchGuard.java b/java28-features/behaviour/SwitchGuard.java new file mode 100644 index 0000000..9c0d96e --- /dev/null +++ b/java28-features/behaviour/SwitchGuard.java @@ -0,0 +1,10 @@ +class SwitchGuard { + static boolean check(String s) throws Exception { return s.isEmpty(); } + + static String classify(Object o) { + return switch (o) { + case String s when check(s) -> "empty"; + default -> "other"; + }; + } +} diff --git a/java28-features/broken/EarlyConstruction.java b/java28-features/broken/EarlyConstruction.java new file mode 100644 index 0000000..53046f6 --- /dev/null +++ b/java28-features/broken/EarlyConstruction.java @@ -0,0 +1,9 @@ +// A value class must set its fields before the superclass constructor runs. +value class Account { + private final long id; + + Account(long id) { + super(); + this.id = id; + } +} diff --git a/java28-features/broken/RecordThis.java b/java28-features/broken/RecordThis.java new file mode 100644 index 0000000..5f2a4f8 --- /dev/null +++ b/java28-features/broken/RecordThis.java @@ -0,0 +1,13 @@ +// An ordinary (identity) record. No value classes anywhere in this file. +import java.util.List; + +record Node(String label, List edges) { + static void nullCheck(Object arg, Object owner) { + if (arg == null) throw new IllegalArgumentException("null arg for " + owner); + } + + public Node { + nullCheck(label, this); + nullCheck(edges, this); + } +} diff --git a/java28-features/output/00-environment.txt b/java28-features/output/00-environment.txt new file mode 100644 index 0000000..87ecbbf --- /dev/null +++ b/java28-features/output/00-environment.txt @@ -0,0 +1,12 @@ +$ java -version +openjdk version "28-ea" 2027-03-23 +OpenJDK Runtime Environment (build 28-ea+26-2195) +OpenJDK 64-Bit Server VM (build 28-ea+26-2195, mixed mode, sharing) +$ JDK 27 comparison build +openjdk version "27.0.1.1" 2026-11-17 +OpenJDK Runtime Environment (build 27.0.1.1+4-22) +OpenJDK 64-Bit Server VM (build 27.0.1.1+4-22, mixed mode, sharing) +$ nproc +2 +$ uname -sm +Linux x86_64 diff --git a/java28-features/output/01-value-classes.txt b/java28-features/output/01-value-classes.txt new file mode 100644 index 0000000..da84761 --- /dev/null +++ b/java28-features/output/01-value-classes.txt @@ -0,0 +1,14 @@ +$ java --enable-preview src/ValueClassDemo.java +value record a == b : true +ordinary record a == b: false +Money has identity : false +Integer 1996 == 1996 : true +IdentityException: Cannot synchronize on an instance of value class java.lang.Integer + +$ java src/IntegerEquality.java +x == y : false +x.equals(y) : true + +$ java --enable-preview src/IntegerEquality.java +x == y : true +x.equals(y) : true diff --git a/java28-features/output/02-preview-changes-records.txt b/java28-features/output/02-preview-changes-records.txt new file mode 100644 index 0000000..001a843 --- /dev/null +++ b/java28-features/output/02-preview-changes-records.txt @@ -0,0 +1,12 @@ +$ javac broken/RecordThis.java +exit 0 + +$ javac --enable-preview --release 28 broken/RecordThis.java +broken/RecordThis.java:10: error: reference to this may only appear after an explicit constructor invocation + nullCheck(label, this); + ^ +broken/RecordThis.java:11: error: reference to this may only appear after an explicit constructor invocation + nullCheck(edges, this); + ^ +2 errors +exit 1 diff --git a/java28-features/output/03-strict-fields.txt b/java28-features/output/03-strict-fields.txt new file mode 100644 index 0000000..87186a0 --- /dev/null +++ b/java28-features/output/03-strict-fields.txt @@ -0,0 +1,17 @@ +$ javac --enable-preview --release 28 src/StrictFields.java +Note: src/StrictFields.java uses preview features of Java SE 28. +Note: Recompile with -Xlint:preview for details. +$ java --enable-preview -cp classes StrictFields classes +StrictFields$Point x flags=0x0812 strictly-initialized=true +StrictFields$Point y flags=0x0812 strictly-initialized=true +StrictFields$Plain x flags=0x0812 strictly-initialized=true +StrictFields$Plain y flags=0x0812 strictly-initialized=true + +$ javac --enable-preview --release 28 broken/EarlyConstruction.java +broken/EarlyConstruction.java:6: error: strict field id is not initialized before the supertype constructor has been called + super(); + ^ +Note: broken/EarlyConstruction.java uses preview features of Java SE 28. +Note: Recompile with -Xlint:preview for details. +1 error +exit 1 diff --git a/java28-features/output/04-json.txt b/java28-features/output/04-json.txt new file mode 100644 index 0000000..1f93f7f --- /dev/null +++ b/java28-features/output/04-json.txt @@ -0,0 +1,10 @@ +$ java --add-modules jdk.incubator.json src/JsonDemo.java +WARNING: Using incubator modules: jdk.incubator.json +service : orders +replicas : 3 +tags : [java, jdk28] +owner : (none) +missing : (absent) +JsonValueException: JsonNumber is not a JsonString. Path: "{replicas". Location: line 0, position 31. +JsonParseException: Duplicate member name: "a" was already parsed. Path: "{". Location: line 0, position 7. +{"ok":true} diff --git a/java28-features/output/05-structured-concurrency.txt b/java28-features/output/05-structured-concurrency.txt new file mode 100644 index 0000000..2e78218 --- /dev/null +++ b/java28-features/output/05-structured-concurrency.txt @@ -0,0 +1,9 @@ +$ java src/StructuredDemo.java +both succeed: + user ok, order ok +one fails: + user was cancelled + join() threw ExecutionException: order service is down +first success wins: + mirror-A was cancelled + winner: mirror-B ok diff --git a/java28-features/output/06-pem.txt b/java28-features/output/06-pem.txt new file mode 100644 index 0000000..af60084 --- /dev/null +++ b/java28-features/output/06-pem.txt @@ -0,0 +1,7 @@ +$ java src/PemDemo.java +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEA2nyOc4Zr8uZvwioD42icFwInLORdN4/VF2xQIrgpUM8= +-----END PUBLIC KEY----- +public key round trip : true +-----BEGIN ENCRYPTED PRIVATE KEY----- +private key round trip: true diff --git a/java28-features/output/07-lazy-constants.txt b/java28-features/output/07-lazy-constants.txt new file mode 100644 index 0000000..9b82da2 --- /dev/null +++ b/java28-features/output/07-lazy-constants.txt @@ -0,0 +1,7 @@ +$ java --enable-preview src/LazyDemo.java +before first get(), computations = 0 +loaded after 1000 concurrent get() calls, computations = 1 +size without computing anything: 5 + computing element 3 +sq9 +sq9 diff --git a/java28-features/output/08-vector.txt b/java28-features/output/08-vector.txt new file mode 100644 index 0000000..e7a7b65 --- /dev/null +++ b/java28-features/output/08-vector.txt @@ -0,0 +1,19 @@ +$ java --add-modules jdk.incubator.vector src/VectorDemo.java +WARNING: Using incubator modules: jdk.incubator.vector +lanes per vector : 16 +sum 1..1003 : 503506 + +$ JDK 28: java --add-modules jdk.incubator.vector src/Float16Demo.java +WARNING: Using incubator modules: jdk.incubator.vector +Species[Float16, 8, S_128_BIT] + +$ JDK 27: java --add-modules jdk.incubator.vector src/Float16Demo.java +WARNING: Using incubator modules: jdk.incubator.vector +src/Float16Demo.java:5: error: cannot find symbol + var species = Float16Vector.SPECIES_128; + ^ + symbol: variable Float16Vector + location: class Float16Demo +1 error +error: compilation failed +exit 1 diff --git a/java28-features/output/09-zgc.txt b/java28-features/output/09-zgc.txt new file mode 100644 index 0000000..ce2987b --- /dev/null +++ b/java28-features/output/09-zgc.txt @@ -0,0 +1,37 @@ +$ JDK 27: java -XX:+UseZGC -Xlog:gc+init HeapProbe +Large Page Support: Disabled +Min Capacity: 8M +Initial Capacity: 8M +Max Capacity: 1536M +Soft Max Capacity: 1382M +init=8M max=1536M +collector bean: ZGC Minor Cycles +collector bean: ZGC Minor Pauses +collector bean: ZGC Major Cycles +collector bean: ZGC Major Pauses + +$ JDK 28: java -XX:+UseZGC -Xlog:gc+init HeapProbe +Large Page Support: Enabled (Transparent, JVM enforced) +Min Capacity: 8M +Initial Capacity: 8M +Max Capacity: 1536M +Soft Max Capacity: 1382M +Heap Sizing: Fixed +init=8M max=1536M +collector bean: ZGC Minor Cycles +collector bean: ZGC Minor Pauses +collector bean: ZGC Major Cycles +collector bean: ZGC Major Pauses + +$ JDK 28: java -XX:+UseZGC -XX:+ZAdaptiveHeapSizing -Xlog:gc+init HeapProbe +Large Page Support: Enabled (Transparent, JVM enforced) +Min Capacity: 2M +Initial Capacity: 2M +Max Capacity: 8022M +Heap Sizing: Adaptive (Implicit Boundaries) +init=2M max=6144M +collector bean: ZGC Minor Cycles +collector bean: ZGC Minor Pauses +collector bean: ZGC Major Cycles +collector bean: ZGC Major Pauses + diff --git a/java28-features/output/10-shenandoah.txt b/java28-features/output/10-shenandoah.txt new file mode 100644 index 0000000..3fac05d --- /dev/null +++ b/java28-features/output/10-shenandoah.txt @@ -0,0 +1,4 @@ +$ java -XX:+UseShenandoahGC -version +Error occurred during initialization of VM +Option -XX:+UseShenandoahGC not supported +exit 1 diff --git a/java28-features/output/11-aot-code.txt b/java28-features/output/11-aot-code.txt new file mode 100644 index 0000000..c53a339 --- /dev/null +++ b/java28-features/output/11-aot-code.txt @@ -0,0 +1,21 @@ +$ java -XX:AOTCacheOutput=app.aot -cp app.jar AotApp +checksum 183000 +Temporary AOTConfiguration recorded: app.aot.config +Reading AOTConfiguration app.aot.config and writing AOTCache app.aot +AOTCache creation is complete: app.aot 12713984 bytes +Removed temporary AOT configuration file app.aot.config +$ java -XX:AOTMode=required -XX:AOTCache=app.aot -XX:+PrintCompilation -cp app.jar AotApp +lines with the A (AOT code) flag: 173 +22 168 A 2 java.lang.Byte::toUnsignedInt (6 bytes) +22 170 A 2 java.lang.Math::floorMod (20 bytes) +22 171 A 2 java.util.ImmutableCollections$SetN::probe (56 bytes) +22 172 A 2 jdk.internal.util.ArraysSupport::vectorizedHashCode (158 bytes) +22 173 A 2 jdk.internal.util.ArraysSupport::hashCodeOfUnsigned (55 bytes) + +$ same run with -XX:+UnlockDiagnosticVMOptions -XX:-AOTCodeCaching +lines with the A (AOT code) flag: 0 + +wall-clock milliseconds for the whole process, 15 interleaved runs each, median [min-max] +no AOT cache 447 [322-634] +AOT cache, AOT code disabled 343 [245-1049] +AOT cache with AOT code 186 [142-417] diff --git a/java28-features/output/12-pkcs12-openssl.txt b/java28-features/output/12-pkcs12-openssl.txt new file mode 100644 index 0000000..2f53263 --- /dev/null +++ b/java28-features/output/12-pkcs12-openssl.txt @@ -0,0 +1,27 @@ +$ JDK 27: keytool -genkeypair -storetype PKCS12 ... ; openssl pkcs12 -info -noout +OpenSSL 3.0.13 30 Jan 2024 (Library: OpenSSL 3.0.13 30 Jan 2024) +MAC: sha256, Iteration 10000 +MAC length: 32, salt length: 20 + +$ JDK 28: keytool -genkeypair -storetype PKCS12 ... ; openssl pkcs12 -info -noout +OpenSSL 3.0.13 30 Jan 2024 (Library: OpenSSL 3.0.13 30 Jan 2024) +MAC: PBMAC1, Iteration 1 +MAC length: 32, salt length: 8 +Mac verify error: invalid password? +error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:../crypto/evp/evp_fetch.c:386:Global default library context, Algorithm (PBMAC1 : 0), Properties () +error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:../crypto/evp/evp_fetch.c:386:Global default library context, Algorithm (PBMAC1 : 0), Properties () + +$ JDK 27 keytool reading the JDK 28 keystore +Keystore type: PKCS12 +demo, Dec 3, 2026, PrivateKeyEntry, + +$ older keytool reading the JDK 28 keystore: openjdk version "25.0.5.1" 2026-11-17 LTS +Keystore type: PKCS12 +demo, Dec 3, 2026, PrivateKeyEntry, + +$ older keytool reading the JDK 28 keystore: openjdk version "21.0.13.1" 2026-11-17 +keytool error: java.io.IOException: Integrity check failed: java.security.NoSuchAlgorithmException: Algorithm HmacPBE1.2.840.113549.1.5.14 not available + +$ JDK 28: keytool -J-Dkeystore.pkcs12.macAlgorithm=HmacPBESHA256 -genkeypair ... ; openssl pkcs12 -info -noout +MAC: sha256, Iteration 10000 +MAC length: 32, salt length: 20 diff --git a/java28-features/output/13-behaviour-changes.txt b/java28-features/output/13-behaviour-changes.txt new file mode 100644 index 0000000..ba02118 --- /dev/null +++ b/java28-features/output/13-behaviour-changes.txt @@ -0,0 +1,24 @@ +$ JDK 27: java behaviour/Behaviour.java +-- ListFormat with single quotes in a custom pattern +[ {0}, foo ] +-- RSA/ECB/PKCS1Padding +cipher initialised +-- canonical size_t layout +j8 equals JAVA_LONG: true +-- ReflectionFactory on a non-serializable class +one-arg : Behaviour$NotSerializable() +two-arg : returned a constructor + +$ JDK 28: java behaviour/Behaviour.java +-- ListFormat with single quotes in a custom pattern +[ 'bar', foo ] +-- RSA/ECB/PKCS1Padding +WARNING: An outdated Cipher algorithm has been called by Behaviour (file:behaviour/Behaviour.java) +WARNING: RSA/ECB/PKCS1Padding will be disabled by default in a future release +cipher initialised +-- canonical size_t layout +uj8 equals JAVA_LONG: false +-- ReflectionFactory on a non-serializable class +one-arg : null +two-arg : UnsupportedOperationException: Run with -Djdk.reflect.allowNonSerializableConstruction=true to temporarily re-enable this method + diff --git a/java28-features/output/14-javac-changes.txt b/java28-features/output/14-javac-changes.txt new file mode 100644 index 0000000..e55c674 --- /dev/null +++ b/java28-features/output/14-javac-changes.txt @@ -0,0 +1,20 @@ +$ JDK 27: javac behaviour/RawConditional.java +exit 0 + +$ JDK 28: javac behaviour/RawConditional.java +behaviour/RawConditional.java:5: error: incompatible types: Object cannot be converted to Integer + return (b ? parameterized : raw).get(0); + ^ +1 error +exit 1 + +$ JDK 27: javac behaviour/SwitchGuard.java +exit 0 + +$ JDK 28: javac behaviour/SwitchGuard.java +behaviour/SwitchGuard.java:6: error: unreported exception Exception; must be caught or declared to be thrown + case String s when check(s) -> "empty"; + ^ +1 error +exit 1 + diff --git a/java28-features/output/15-finals-on-jdk27.txt b/java28-features/output/15-finals-on-jdk27.txt new file mode 100644 index 0000000..1356ab6 --- /dev/null +++ b/java28-features/output/15-finals-on-jdk27.txt @@ -0,0 +1,16 @@ +$ JDK 27: java src/StructuredDemo.java (no flags) +src/StructuredDemo.java:2: error: StructuredTaskScope is a preview API and is disabled by default. +import java.util.concurrent.StructuredTaskScope.Joiner; + ^ + (use --enable-preview to enable preview APIs) +src/StructuredDemo.java:2: error: Joiner is a preview API and is disabled by default. +import java.util.concurrent.StructuredTaskScope.Joiner; + +$ JDK 27: java src/PemDemo.java (no flags) +src/PemDemo.java:4: error: PEMDecoder is a preview API and is disabled by default. +import java.security.PEMDecoder; + ^ + (use --enable-preview to enable preview APIs) +src/PemDemo.java:5: error: PEMEncoder is a preview API and is disabled by default. +import java.security.PEMEncoder; + diff --git a/java28-features/output/16-platform.txt b/java28-features/output/16-platform.txt new file mode 100644 index 0000000..ed32b33 --- /dev/null +++ b/java28-features/output/16-platform.txt @@ -0,0 +1,2 @@ +$ java src/PlatformCheck.java +Linux / amd64 -> not affected by JEP 541 diff --git a/java28-features/run.sh b/java28-features/run.sh new file mode 100755 index 0000000..52eb946 --- /dev/null +++ b/java28-features/run.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Regenerates every transcript in output/. +# JDK27=/path/to/jdk-27 JDK28=/path/to/jdk-28-ea [JDK25=... JDK21=...] ./run.sh +# JDK28 is an early-access build; behaviour can change between builds. openssl is needed for step 12. +set -uo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)"; cd "$HERE" +: "${JDK27:?set JDK27}" "${JDK28:?set JDK28}" +OUT="$HERE/output"; mkdir -p "$OUT"; W="$(mktemp -d)"; trap 'rm -rf "$W"' EXIT +J="$JDK28/bin" +# Drop the JVM's "Picked up ..._OPTIONS" banners and machine-specific path prefixes. +clean() { grep -v -E '^Picked up (JAVA_TOOL_OPTIONS|_JAVA_OPTIONS)' | sed -e "s#$HERE/##g" -e "s#$W/##g" -e "s#$JDK28#\$JDK28#g" -e "s#$JDK27#\$JDK27#g"; } +say() { echo "\$ $*"; } +# run NAME FILE: execute a step function and save its transcript +step() { echo "== $1"; "$2" 2>&1 | clean > "$OUT/$1.txt"; } + +env_info() { say java -version; "$J/java" -version; say "JDK 27 comparison build"; "$JDK27/bin/java" -version; say nproc; nproc; say uname -sm; uname -sm; } + +value_classes() { + say java --enable-preview src/ValueClassDemo.java; "$J/java" --enable-preview src/ValueClassDemo.java + echo; say java src/IntegerEquality.java; "$J/java" src/IntegerEquality.java + echo; say java --enable-preview src/IntegerEquality.java; "$J/java" --enable-preview src/IntegerEquality.java +} + +preview_records() { + say javac broken/RecordThis.java; "$J/javac" -d "$W/r1" broken/RecordThis.java; echo "exit $?" + echo; say javac --enable-preview --release 28 broken/RecordThis.java; "$J/javac" --enable-preview --release 28 -d "$W/r2" broken/RecordThis.java; echo "exit $?" +} + +strict_fields() { + say javac --enable-preview --release 28 src/StrictFields.java; "$J/javac" --enable-preview --release 28 -d "$W/s" src/StrictFields.java + say java --enable-preview -cp classes StrictFields classes; "$J/java" --enable-preview -cp "$W/s" StrictFields "$W/s" + echo; say javac --enable-preview --release 28 broken/EarlyConstruction.java; "$J/javac" --enable-preview --release 28 -d "$W/e" broken/EarlyConstruction.java; echo "exit $?" +} + +json() { say java --add-modules jdk.incubator.json src/JsonDemo.java; "$J/java" --add-modules jdk.incubator.json src/JsonDemo.java; } +structured() { say java src/StructuredDemo.java; "$J/java" src/StructuredDemo.java; } +pem() { say java src/PemDemo.java; "$J/java" src/PemDemo.java; } +lazy() { say java --enable-preview src/LazyDemo.java; "$J/java" --enable-preview src/LazyDemo.java; } +vector() { + say java --add-modules jdk.incubator.vector src/VectorDemo.java; "$J/java" --add-modules jdk.incubator.vector src/VectorDemo.java + echo; say "JDK 28: java --add-modules jdk.incubator.vector src/Float16Demo.java"; "$J/java" --add-modules jdk.incubator.vector src/Float16Demo.java + echo; say "JDK 27: java --add-modules jdk.incubator.vector src/Float16Demo.java"; "$JDK27/bin/java" --add-modules jdk.incubator.vector src/Float16Demo.java; echo "exit $?" +} + +zgc() { + "$J/javac" -d "$W/h" src/HeapProbe.java + for spec in "27|$JDK27|-XX:+UseZGC" "28|$JDK28|-XX:+UseZGC" "28|$JDK28|-XX:+UseZGC -XX:+ZAdaptiveHeapSizing"; do + IFS='|' read -r v home flags <<<"$spec" + say "JDK $v: java $flags -Xlog:gc+init HeapProbe" + "$home/bin/javac" -d "$W/h$v" src/HeapProbe.java + "$home/bin/java" $flags -Xlog:gc+init -cp "$W/h$v" HeapProbe | grep -E 'Large Page|Capacity|Heap Sizing|init=|collector bean' | sed 's/^\[[^]]*\]\[info\]\[gc,init\] //' + echo + done +} + +shenandoah() { + say java -XX:+UseShenandoahGC -version; "$J/java" -XX:+UseShenandoahGC -version; echo "exit $?" +} + +aot() { + "$J/javac" -d "$W/a" src/AotApp.java; "$J/jar" cf "$W/app.jar" -C "$W/a" . + say java -XX:AOTCacheOutput=app.aot -cp app.jar AotApp; (cd "$W" && "$J/java" -XX:AOTCacheOutput=app.aot -cp app.jar AotApp | grep -v '^Launching') + say java -XX:AOTMode=required -XX:AOTCache=app.aot -XX:+PrintCompilation -cp app.jar AotApp + (cd "$W" && "$J/java" -XX:AOTMode=required -XX:AOTCache=app.aot -XX:+PrintCompilation -cp app.jar AotApp > pc.log) + echo "lines with the A (AOT code) flag: $(grep -c -E '^ *[0-9]+ +[0-9]+ +A ' "$W/pc.log")" + grep -E '^ *[0-9]+ +[0-9]+ +A ' "$W/pc.log" | head -5 + echo + say "same run with -XX:+UnlockDiagnosticVMOptions -XX:-AOTCodeCaching" + (cd "$W" && "$J/java" -XX:+UnlockDiagnosticVMOptions -XX:-AOTCodeCaching -XX:AOTCache=app.aot -XX:+PrintCompilation -cp app.jar AotApp > pc2.log) + echo "lines with the A (AOT code) flag: $(grep -c -E '^ *[0-9]+ +[0-9]+ +A ' "$W/pc2.log")" + echo + echo "wall-clock milliseconds for the whole process, 15 interleaved runs each, median [min-max]" + : > "$W/n"; : > "$W/p"; : > "$W/c" + once() { local f=$1; shift; local s e; s=$(date +%s%N); (cd "$W" && "$J/java" "$@" -cp app.jar AotApp >/dev/null 2>&1) || echo FAILED; e=$(date +%s%N); echo $(( (e-s)/1000000 )) >> "$W/$f"; } + for i in $(seq 15); do + once n -XX:AOTMode=off + once p -XX:+UnlockDiagnosticVMOptions -XX:-AOTCodeCaching -XX:AOTCache=app.aot + once c -XX:AOTCache=app.aot + done + stat() { sort -n "$W/$2" | awk -v l="$1" '{a[NR]=$1} END {printf "%-32s %4d [%d-%d]\n", l, a[8], a[1], a[NR]}'; } + stat "no AOT cache" n; stat "AOT cache, AOT code disabled" p; stat "AOT cache with AOT code" c +} + +behaviour() { + for v in 27 28; do h="JDK$v"; say "JDK $v: java behaviour/Behaviour.java"; "${!h}/bin/java" behaviour/Behaviour.java; echo; done +} + +javac_changes() { + for f in RawConditional SwitchGuard; do for v in 27 28; do h="JDK$v"; say "JDK $v: javac behaviour/$f.java"; "${!h}/bin/javac" -d "$W/j$v" "behaviour/$f.java"; echo "exit $?"; echo; done; done +} + +finals_on_27() { + for f in StructuredDemo PemDemo; do say "JDK 27: java src/$f.java (no flags)"; "$JDK27/bin/java" "src/$f.java" 2>&1 | head -8; echo; done +} + +pkcs12() { + for v in 27 28; do h="JDK$v" + say "JDK $v: keytool -genkeypair -storetype PKCS12 ... ; openssl pkcs12 -info -noout" + "${!h}/bin/keytool" -genkeypair -alias demo -keyalg EC -dname CN=demo -storetype PKCS12 -keystore "$W/k$v.p12" -storepass changeit >/dev/null 2>&1 + openssl version + openssl pkcs12 -info -noout -in "$W/k$v.p12" -passin pass:changeit 2>&1 | grep -E '^MAC|verify error|Algorithm \(' | sed 's/^[0-9A-F]*:error:/error:/' + echo + done + say "JDK 27 keytool reading the JDK 28 keystore" + "$JDK27/bin/keytool" -list -keystore "$W/k28.p12" -storepass changeit | grep -E 'Keystore type|PrivateKeyEntry' + echo + # optional: older runtimes, if given + for old in "${JDK25:-}" "${JDK21:-}"; do + [ -n "$old" ] || continue + say "older keytool reading the JDK 28 keystore: $("$old/bin/java" -version 2>&1 | grep ' version ')" + "$old/bin/keytool" -list -keystore "$W/k28.p12" -storepass changeit 2>&1 | grep -E 'Keystore type|PrivateKeyEntry|error' + echo + done + say "JDK 28: keytool -J-Dkeystore.pkcs12.macAlgorithm=HmacPBESHA256 -genkeypair ... ; openssl pkcs12 -info -noout" + "$J/keytool" -J-Dkeystore.pkcs12.macAlgorithm=HmacPBESHA256 -genkeypair -alias demo -keyalg EC -dname CN=demo -storetype PKCS12 -keystore "$W/kold.p12" -storepass changeit >/dev/null 2>&1 + openssl pkcs12 -info -noout -in "$W/kold.p12" -passin pass:changeit 2>&1 | grep -E '^MAC|verify error' +} + +platform() { say java src/PlatformCheck.java; "$J/java" src/PlatformCheck.java; } + +step 00-environment env_info +step 01-value-classes value_classes +step 02-preview-changes-records preview_records +step 03-strict-fields strict_fields +step 04-json json +step 05-structured-concurrency structured +step 06-pem pem +step 07-lazy-constants lazy +step 08-vector vector +step 09-zgc zgc +step 10-shenandoah shenandoah +step 11-aot-code aot +step 12-pkcs12-openssl pkcs12 +step 13-behaviour-changes behaviour +step 14-javac-changes javac_changes +step 15-finals-on-jdk27 finals_on_27 +step 16-platform platform diff --git a/java28-features/src/AotApp.java b/java28-features/src/AotApp.java new file mode 100644 index 0000000..be03b48 --- /dev/null +++ b/java28-features/src/AotApp.java @@ -0,0 +1,19 @@ +// JEP 544: Ahead-of-Time Code Compilation. A small workload for the training and production runs. +import java.util.*; +import java.util.stream.*; + +public class AotApp { + public static void main(String[] args) { + long total = 0; + for (int round = 0; round < 300; round++) { + Map> byLength = IntStream.range(0, 2000) + .mapToObj(i -> "item-" + Integer.toHexString(i * 31)) + .collect(Collectors.groupingBy(String::length)); + for (var list : byLength.values()) { + Collections.sort(list); + total += String.join(",", list).hashCode() & 0xff; + } + } + System.out.println("checksum " + total); + } +} diff --git a/java28-features/src/Float16Demo.java b/java28-features/src/Float16Demo.java new file mode 100644 index 0000000..f25cf24 --- /dev/null +++ b/java28-features/src/Float16Demo.java @@ -0,0 +1,7 @@ +// The one change in JEP 548: vectors of 16-bit floating point lanes. +import jdk.incubator.vector.*; + +void main() { + var species = Float16Vector.SPECIES_128; + IO.println(species); +} diff --git a/java28-features/src/HeapProbe.java b/java28-features/src/HeapProbe.java new file mode 100644 index 0000000..a218ac2 --- /dev/null +++ b/java28-features/src/HeapProbe.java @@ -0,0 +1,10 @@ +// Prints the heap the JVM actually chose. Used for the GC runs (JEP 535, 545, 546). +import java.lang.management.ManagementFactory; + +public class HeapProbe { + public static void main(String[] args) { + var heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); + System.out.println("init=" + (heap.getInit() >> 20) + "M max=" + (heap.getMax() >> 20) + "M"); + ManagementFactory.getGarbageCollectorMXBeans().forEach(b -> System.out.println("collector bean: " + b.getName())); + } +} diff --git a/java28-features/src/IntegerEquality.java b/java28-features/src/IntegerEquality.java new file mode 100644 index 0000000..5394247 --- /dev/null +++ b/java28-features/src/IntegerEquality.java @@ -0,0 +1,6 @@ +// The same two lines with and without --enable-preview. No new syntax, different answer. +void main() { + Integer x = 1996, y = 1996; + IO.println("x == y : " + (x == y)); + IO.println("x.equals(y) : " + x.equals(y)); +} diff --git a/java28-features/src/JsonDemo.java b/java28-features/src/JsonDemo.java new file mode 100644 index 0000000..01460c5 --- /dev/null +++ b/java28-features/src/JsonDemo.java @@ -0,0 +1,26 @@ +// JEP 540: Simple JSON API (Incubator). Needs --add-modules jdk.incubator.json +import jdk.incubator.json.*; + +void main() { + String doc = """ + {"service":"orders","replicas":3,"tags":["java","jdk28"],"owner":null} + """; + JsonValue root = Json.parse(doc); + IO.println("service : " + root.get("service").asString()); + IO.println("replicas : " + root.get("replicas").asInt()); + IO.println("tags : " + root.get("tags").asList().stream().map(JsonValue::asString).toList()); + IO.println("owner : " + root.tryGet("owner").flatMap(JsonValue::tryValue).map(JsonValue::asString).orElse("(none)")); + IO.println("missing : " + root.tryGet("region").map(JsonValue::asString).orElse("(absent)")); + + try { + root.get("replicas").asString(); + } catch (JsonValueException e) { + IO.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + try { + Json.parse("{\"a\":1,\"a\":2}"); + } catch (JsonParseException e) { + IO.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + IO.println(JsonObject.of(Map.of("ok", JsonBoolean.of(true)))); +} diff --git a/java28-features/src/LazyDemo.java b/java28-features/src/LazyDemo.java new file mode 100644 index 0000000..fdb3ace --- /dev/null +++ b/java28-features/src/LazyDemo.java @@ -0,0 +1,27 @@ +// JEP 547: Lazy Constants (Fourth Preview). Run with --enable-preview. +import java.util.concurrent.atomic.AtomicInteger; + +static final AtomicInteger CALLS = new AtomicInteger(); + +static final LazyConstant CONFIG = LazyConstant.of(() -> { + CALLS.incrementAndGet(); + return "loaded"; +}); + +void main() throws Exception { + IO.println("before first get(), computations = " + CALLS.get()); + var threads = new ArrayList(); + for (int i = 0; i < 1000; i++) { + threads.add(Thread.ofVirtual().start(() -> CONFIG.get())); + } + for (var t : threads) t.join(); + IO.println(CONFIG.get() + " after 1000 concurrent get() calls, computations = " + CALLS.get()); + + List squares = List.ofLazy(5, i -> { + IO.println(" computing element " + i); + return "sq" + (i * i); + }); + IO.println("size without computing anything: " + squares.size()); + IO.println(squares.get(3)); + IO.println(squares.get(3)); +} diff --git a/java28-features/src/PemDemo.java b/java28-features/src/PemDemo.java new file mode 100644 index 0000000..2bee28c --- /dev/null +++ b/java28-features/src/PemDemo.java @@ -0,0 +1,22 @@ +// JEP 542: PEM Encodings of Cryptographic Objects, final in JDK 28. No flags. +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PEMDecoder; +import java.security.PEMEncoder; +import java.security.PublicKey; +import java.security.PrivateKey; + +void main() throws Exception { + KeyPair pair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + + String publicPem = PEMEncoder.of().encodeToString(pair.getPublic()); + IO.print(publicPem); + PublicKey back = PEMDecoder.of().decode(publicPem, PublicKey.class); + IO.println("public key round trip : " + back.equals(pair.getPublic())); + + char[] password = "change-me".toCharArray(); + String locked = PEMEncoder.of().withEncryption(password).encodeToString(pair.getPrivate()); + IO.println(locked.lines().findFirst().orElseThrow()); + PrivateKey opened = PEMDecoder.of().withDecryption(password).decode(locked, PrivateKey.class); + IO.println("private key round trip: " + Arrays.equals(opened.getEncoded(), pair.getPrivate().getEncoded())); +} diff --git a/java28-features/src/PlatformCheck.java b/java28-features/src/PlatformCheck.java new file mode 100644 index 0000000..c9678e8 --- /dev/null +++ b/java28-features/src/PlatformCheck.java @@ -0,0 +1,7 @@ +// JEP 541: is this machine on the deprecated macOS/x64 port? +void main() { + String os = System.getProperty("os.name"); + String arch = System.getProperty("os.arch"); + boolean affected = os.startsWith("Mac") && (arch.equals("x86_64") || arch.equals("amd64")); + IO.println(os + " / " + arch + " -> " + (affected ? "macOS/x64: deprecated for removal in JDK 28" : "not affected by JEP 541")); +} diff --git a/java28-features/src/StrictFields.java b/java28-features/src/StrictFields.java new file mode 100644 index 0000000..18ffc34 --- /dev/null +++ b/java28-features/src/StrictFields.java @@ -0,0 +1,23 @@ +// JEP 539: strict field initialization is a JVM feature; javac uses it for value classes. +// Compile this file with --enable-preview, then let it read its own class files. +import java.lang.classfile.ClassFile; +import java.nio.file.Files; +import java.nio.file.Path; + +public class StrictFields { + static final int ACC_STRICT_INIT = 0x0800; + + value record Point(int x, int y) {} + record Plain(int x, int y) {} + + public static void main(String[] args) throws Exception { + for (String name : new String[] {"StrictFields$Point", "StrictFields$Plain"}) { + var model = ClassFile.of().parse(Files.readAllBytes(Path.of(args[0], name + ".class"))); + for (var field : model.fields()) { + int mask = field.flags().flagsMask(); + System.out.printf("%-20s %s flags=0x%04x strictly-initialized=%b%n", + name, field.fieldName().stringValue(), mask, (mask & ACC_STRICT_INIT) != 0); + } + } + } +} diff --git a/java28-features/src/StructuredDemo.java b/java28-features/src/StructuredDemo.java new file mode 100644 index 0000000..aaf538b --- /dev/null +++ b/java28-features/src/StructuredDemo.java @@ -0,0 +1,39 @@ +// JEP 543: Structured Concurrency, final in JDK 28. No flags. +import java.util.concurrent.StructuredTaskScope.Joiner; + +String fetch(String what, int millis, boolean fail) throws InterruptedException { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + IO.println(" " + what + " was cancelled"); + throw e; + } + if (fail) throw new IllegalStateException(what + " service is down"); + return what + " ok"; +} + +void main() throws Exception { + IO.println("both succeed:"); + try (var scope = StructuredTaskScope.open()) { + var user = scope.fork(() -> fetch("user", 50, false)); + var order = scope.fork(() -> fetch("order", 80, false)); + scope.join(); + IO.println(" " + user.get() + ", " + order.get()); + } + + IO.println("one fails:"); + try (var scope = StructuredTaskScope.open()) { + scope.fork(() -> fetch("user", 2000, false)); + scope.fork(() -> fetch("order", 50, true)); + scope.join(); + } catch (ExecutionException e) { + IO.println(" join() threw " + e.getClass().getSimpleName() + ": " + e.getCause().getMessage()); + } + + IO.println("first success wins:"); + try (var scope = StructuredTaskScope.open(Joiner.anySuccessfulOrThrow())) { + scope.fork(() -> fetch("mirror-A", 2000, false)); + scope.fork(() -> fetch("mirror-B", 50, false)); + IO.println(" winner: " + scope.join()); + } +} diff --git a/java28-features/src/ValueClassDemo.java b/java28-features/src/ValueClassDemo.java new file mode 100644 index 0000000..e0cf228 --- /dev/null +++ b/java28-features/src/ValueClassDemo.java @@ -0,0 +1,24 @@ +// JEP 401: Value Objects (Preview). Run with --enable-preview on JDK 28. +value record Money(String currency, long paise) {} + +record Ordinary(String currency, long paise) {} + +void main() { + Money a = new Money("INR", 500); + Money b = new Money("INR", 500); + IO.println("value record a == b : " + (a == b)); + IO.println("ordinary record a == b: " + (new Ordinary("INR", 500) == new Ordinary("INR", 500))); + IO.println("Money has identity : " + Objects.hasIdentity(a)); + + Integer x = 1996, y = 1996; + IO.println("Integer 1996 == 1996 : " + (x == y)); + + Object o = x; // hide the static type from javac + try { + synchronized (o) { + IO.println("locked an Integer"); + } + } catch (IdentityException e) { + IO.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } +} diff --git a/java28-features/src/VectorDemo.java b/java28-features/src/VectorDemo.java new file mode 100644 index 0000000..9932346 --- /dev/null +++ b/java28-features/src/VectorDemo.java @@ -0,0 +1,21 @@ +// JEP 548: Vector API (Thirteenth Incubator). Needs --add-modules jdk.incubator.vector +import jdk.incubator.vector.*; + +static final VectorSpecies SPECIES = IntVector.SPECIES_PREFERRED; + +static int sum(int[] data) { + var acc = IntVector.zero(SPECIES); + int i = 0; + for (; i < SPECIES.loopBound(data.length); i += SPECIES.length()) { + acc = acc.add(IntVector.fromArray(SPECIES, data, i)); + } + int total = acc.reduceLanes(VectorOperators.ADD); + for (; i < data.length; i++) total += data[i]; + return total; +} + +void main() { + int[] data = java.util.stream.IntStream.rangeClosed(1, 1003).toArray(); + IO.println("lanes per vector : " + SPECIES.length()); + IO.println("sum 1..1003 : " + sum(data)); +}