Compare commits
14
Commits
c3cc57f482
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d05be0c2c | ||
|
|
94f8a0e003 | ||
|
|
3502fd7804 | ||
|
|
d4b8552957 | ||
|
|
c0062ea398 | ||
|
|
de2660e998 | ||
|
|
1fb1455734 | ||
|
|
876ae1bb5c | ||
|
|
f7b6c1efca | ||
|
|
ecceaa8b32 | ||
|
|
41101bea40 | ||
|
|
eca73ad544 | ||
|
|
c93a1fffbb | ||
|
|
2e25042a68 |
@@ -17,7 +17,7 @@ ThreadLocal (JEP 506)**. Every number and transcript in the post comes from a fi
|
|||||||
|
|
||||||
Next LTS: Java 29, September 2027 (Oracle Java SE Support Roadmap). Layout: `g1-container/`, `object-headers/`, `jep-tour/` (27 features and `broken/` 26-era sources),
|
Next LTS: Java 29, September 2027 (Oracle Java SE Support Roadmap). Layout: `g1-container/`, `object-headers/`, `jep-tour/` (27 features and `broken/` 26-era sources),
|
||||||
`recap26/` (the Java 26 lane), `lanes/` (the 21 to 25 hub demos, the AI prompts in `lanes/prompts/` and the build-file demo in `lanes/upgrade/`), `other-changes/`, `api-diff/`,
|
`recap26/` (the Java 26 lane), `lanes/` (the 21 to 25 hub demos, the AI prompts in `lanes/prompts/` and the build-file demo in `lanes/upgrade/`), `other-changes/`, `api-diff/`,
|
||||||
`gatherers/` (JEP 485, standalone post), `scoped-values/` (JEP 506 vs `ThreadLocal`, standalone post). `jdk27-perf/` (the same Spring Boot service on JDK 25 and 27: footprint, throughput, p99; its README and `output/` replace a `docs/` folder).
|
`gatherers/` (JEP 485, standalone post), `scoped-values/` (JEP 506 vs `ThreadLocal`, standalone post). `jdk27-perf/` (the same Spring Boot service on JDK 25 and 27: footprint, throughput, p99; its README and `output/` replace a `docs/` folder). `java25-features/` (the 18 JEPs of JDK 25 with runnable demos; its README and `output/` replace a `docs/` folder). `gc-basics/` (how Java garbage collection works, with five collectors measured on JDK 25, 27 and 28 EA; its README and `output/` replace a `docs/` folder).
|
||||||
|
|
||||||
## Quickstart
|
## Quickstart
|
||||||
|
|
||||||
@@ -70,6 +70,17 @@ These modules keep only sources, a `run.sh` and their transcripts (`output/`). T
|
|||||||
| [`lazy-constants/`](lazy-constants) | Lazy Constants in JDK 27 (JEP 531): Replacing Double-Checked Locking | `LazyConstant` against the holder idiom and double-checked locking, the 26 to 27 failure-semantics change, `List`/`Map`/`Set.ofLazy`, the preview-flag traps and a JMH read-path benchmark |
|
| [`lazy-constants/`](lazy-constants) | Lazy Constants in JDK 27 (JEP 531): Replacing Double-Checked Locking | `LazyConstant` against the holder idiom and double-checked locking, the 26 to 27 failure-semantics change, `List`/`Map`/`Set.ofLazy`, the preview-flag traps and a JMH read-path benchmark |
|
||||||
| [`http3/`](http3) | HTTP/3 in the Java HTTP Client (JEP 517): Migrating from HttpClient 11 | Java 11 code unchanged on 25 and 26, the `HTTP_3` opt-in on client vs request, the three `H3_DISCOVERY` modes, fallback timings (including the 60 s `HTTP_3_URI_ONLY` failure), proxy downgrade, HTTP/1.1 vs 2 vs 3 under iptables packet loss, with a local Hypercorn + aioquic server |
|
| [`http3/`](http3) | HTTP/3 in the Java HTTP Client (JEP 517): Migrating from HttpClient 11 | Java 11 code unchanged on 25 and 26, the `HTTP_3` opt-in on client vs request, the three `H3_DISCOVERY` modes, fallback timings (including the 60 s `HTTP_3_URI_ONLY` failure), proxy downgrade, HTTP/1.1 vs 2 vs 3 under iptables packet loss, with a local Hypercorn + aioquic server |
|
||||||
| [`compact-strings/`](compact-strings) | Compact Strings in Java: Measured with JOL on JDK 25 (plus Compact Object Headers) | the `String` object and its `byte[]` field by field, Latin-1 vs UTF-16 footprint by length, one million strings with and without `-XX:-CompactStrings`, what flips a string to UTF-16 (and what flips it back), compact object headers on JDK 25 (opt-in) vs 27 (default), a JMH comparison of six operations |
|
| [`compact-strings/`](compact-strings) | Compact Strings in Java: Measured with JOL on JDK 25 (plus Compact Object Headers) | the `String` object and its `byte[]` field by field, Latin-1 vs UTF-16 footprint by length, one million strings with and without `-XX:-CompactStrings`, what flips a string to UTF-16 (and what flips it back), compact object headers on JDK 25 (opt-in) vs 27 (default), a JMH comparison of six operations |
|
||||||
|
| [`pem-api/`](pem-api) | PEM Encodings in Java (JEP 538/542): Read and Write Keys and Certificates Without BouncyCastle | `PEMDecoder`/`PEMEncoder` round trips, JWT signing (RS256/ES256/EdDSA) and a TLS server built from PEM files, encrypted PKCS#8 keys, the failure catalogue (wrong target class, SEC1 `EC PRIVATE KEY`, CRLF output), BouncyCastle and Spring Security `RsaKeyConverters` side by side, preview flag on JDK 27 vs the JDK 28 EA build |
|
||||||
|
| [`structured-concurrency-final/`](structured-concurrency-final) | Structured Concurrency Is Final in JDK 28 (JEP 543): From Preview to Production | the thread leak of `ExecutorService` and its fix, every built-in `Joiner`, structure violations, timeouts, a custom joiner, JSON thread dumps, scoped values, `javap` diffs of the API on JDK 25, 26, 27 and 28-ea, the compiler output for six pieces of 25/26-era code, and the preview class-file trap between 27 and 28 |
|
||||||
|
| [`kdf/`](kdf) | Key Derivation Function API in Java (JEP 510): HKDF Explained with Real Examples | `javax.crypto.KDF` final in JDK 25, `HKDF-SHA256/384/512`, extract vs expand, RFC 5869 vectors asserted, a hand-written HKDF and 300 generated cases compared with Python `cryptography` and `openssl kdf`, per-tenant keys with length-prefixed `info`, and the mistakes reproduced (same `info`, ambiguous concatenation, PIN through HKDF vs PBKDF2) |
|
||||||
|
| [`classfile-api/`](classfile-api) | The Java ClassFile API (JEP 484): Read, Generate and Transform Bytecode Without ASM | `java.lang.classfile` final since JDK 24: `parse` and `ClassModel` traversal, `ClassFile.build` with `defineClass` and `defineHiddenClass`, five deliberately broken classes (including swapped exception-table labels that `verify()` misses), timing inserted with `ClassTransform`/`MethodTransform`/`CodeTransform`, the same three jobs in ASM 9.11.1 asserted equal, class-file version limits, a JDK 24/25/26 API diff and a look inside `spring-core` 7.0.10 |
|
||||||
|
| [`jextract/`](jextract) | Calling C from Java with jextract and the FFM API: A Real Library, No JNI | jextract (early-access build for JDK 25) bindings for SQLite 3.45.1, the four arena kinds used wrongly on purpose, `C_POINTER` vs `ADDRESS` (zero-length pointers, and a `SIGSEGV` from `getString` on a NULL pointer), `sqlite3_open` out-parameter, return codes to exceptions, a `sqlite3_exec` upcall (and the JVM exit when it throws), the JDK 25 native-access warning and `--illegal-native-access=deny`, and a JMH comparison of FFM, hand-written JNI and plain Java |
|
||||||
|
| [`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 |
|
||||||
|
| [`java21-to-25/`](java21-to-25) | Java 21 to Java 25 Migration Guide: What Breaks, What to Turn On, and the Upgrade Checklist | classes compiled once on 21 and run on 21 and 25, removed APIs, preview classes, a Maven matrix for Lombok/Mockito/JaCoCo/Spring Boot, pinning, compact object headers, containers (`scripts/`, `output/`) |
|
||||||
|
| [`java8-to-25/`](java8-to-25) | Java 8 to Java 25 Migration Guide: The Long Jump in One Plan | a Java 8 app that breaks nine ways, run on JDK 8, 17 and 25; `javax` vs `jakarta`, the `--release 8` trap, `jdeps`/`jdeprscan` blind spots, 33 JVM options, TLS defaults, Lombok/Mockito/ASM/JaCoCo/Gradle on 25, OpenRewrite `UpgradeToJava25`, bridge classpath and fixed version |
|
||||||
|
|
||||||
## Captured output (`docs/output/`)
|
## Captured output (`docs/output/`)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
target/
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# classfile-api
|
||||||
|
|
||||||
|
Companion code for the ankurm.com article **The Java ClassFile API (JEP 484): Read, Generate and Transform Bytecode Without ASM**
|
||||||
|
(https://ankurm.com/java-classfile-api-jep-484/).
|
||||||
|
|
||||||
|
`java.lang.classfile` was a preview API in JDK 22 and 23 (JEPs 457, 466) and is **final since JDK 24 (JEP 484)**: no `--enable-preview`.
|
||||||
|
Everything here ran on Temurin 25.0.5+8; the API diff also ran on Temurin 24.0.2 and 26.0.2.1. The only dependency is ASM 9.11.1, used by the comparison classes.
|
||||||
|
|
||||||
|
| File | What it shows | Output |
|
||||||
|
|---|---|---|
|
||||||
|
| `Target.java`, `Timings.java` | the class we inspect/instrument, and the sink the injected code calls | |
|
||||||
|
| `ParseDemo.java` | `ClassFile.of().parse`, `ClassModel` traversal, pattern-matching over elements and instructions | `output/01-parse.txt` |
|
||||||
|
| `GenerateDemo.java` | `ClassFile.build`, `verify`, `Lookup.defineClass` vs `defineHiddenClass` | `output/02-generate.txt`, `03-javap-generated.txt` |
|
||||||
|
| `BrokenGenerate.java` | dropped stack maps, wrong return type, stack underflow, swapped exception-table labels | `output/04-broken-generate.txt` |
|
||||||
|
| `TimingTransform.java`, `TransformDemo.java` | `ClassTransform` / `MethodTransform` / `CodeTransform` inserting timing; naive vs exception-safe | `output/05-transform.txt`, `06-javap-instrumented.txt` |
|
||||||
|
| `AsmParse.java`, `AsmGenerate.java`, `AsmInstrument.java`, `AsmGotcha.java` | the same three jobs in ASM 9.11.1, asserted equal; plus the `EXPAND_FRAMES` trap | `output/08`, `09`, `10`, `15` |
|
||||||
|
| `VersionLimits.java` | a newer class file than the reader knows: `java.lang.classfile` vs ASM | `output/11-version-limits.txt` |
|
||||||
|
| `Bench.java` | indicative parse and copy timing on 2000 `java.base` classes (thread CPU time, noisy) | `output/13-bench.txt` |
|
||||||
|
| `scripts/run-all.sh` | API diff of `java.lang.classfile` across JDK 24, 25, 26 | `output/07-api-diff-24-25-26.txt` |
|
||||||
|
| `scripts/spring-core-probe.sh` | what `spring-core` 7.0.10 ships for the ClassFile API | `output/14-spring-core-probe.txt` |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
JDK25=/path/to/jdk-25 JDK24=/path/to/jdk-24 JDK26=/path/to/jdk-26 ./scripts/run-all.sh # JDK24/JDK26 optional; needs Maven for the ASM jars
|
||||||
|
JDK25=/path/to/jdk-25 ./scripts/spring-core-probe.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The demos assert as they go (`PASS`/`FAIL`, non-zero exit on failure), like the other standalone modules; there is no JUnit. Output is byte-stable except `13-bench.txt`.
|
||||||
|
Not reproduced: nothing was run on JDK 22/23 previews.
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.ParseDemo (25.0.5+8-LTS)
|
||||||
|
== header ==
|
||||||
|
bytes : 1488
|
||||||
|
this : demo/Target
|
||||||
|
super : java/lang/Object
|
||||||
|
version : 69.0 (ClassFile.JAVA_25_VERSION = 69)
|
||||||
|
flags : public,super
|
||||||
|
constant pool : 69 slots
|
||||||
|
|
||||||
|
== fields ==
|
||||||
|
final,private name Ljava/lang/String;
|
||||||
|
private calls I
|
||||||
|
|
||||||
|
== methods ==
|
||||||
|
public <init>(Ljava/lang/String;)V
|
||||||
|
public,static fib(I)I
|
||||||
|
public,static sumTo(I)J
|
||||||
|
public greet(Ljava/lang/String;)Ljava/lang/String;
|
||||||
|
public pause(J)V
|
||||||
|
public,static boom()V
|
||||||
|
public,static explode([I)I
|
||||||
|
public calls()I
|
||||||
|
|
||||||
|
== class elements, in file order (the model is a stream of elements) ==
|
||||||
|
AccessFlags
|
||||||
|
ClassFileVersion
|
||||||
|
Superclass
|
||||||
|
Interfaces
|
||||||
|
field name
|
||||||
|
field calls
|
||||||
|
method <init>
|
||||||
|
method fib
|
||||||
|
method sumTo
|
||||||
|
method greet
|
||||||
|
method pause
|
||||||
|
method boom
|
||||||
|
method explode
|
||||||
|
method calls
|
||||||
|
SourceFile=Target.java
|
||||||
|
BoundInnerClassesAttribute
|
||||||
|
|
||||||
|
== fib(I)I, instruction by instruction ==
|
||||||
|
ILOAD_0
|
||||||
|
ICONST_2
|
||||||
|
IF_ICMPGE
|
||||||
|
ILOAD_0
|
||||||
|
GOTO
|
||||||
|
ILOAD_0
|
||||||
|
ICONST_1
|
||||||
|
ISUB
|
||||||
|
INVOKESTATIC demo/Target.fib(I)I
|
||||||
|
ILOAD_0
|
||||||
|
ICONST_2
|
||||||
|
ISUB
|
||||||
|
INVOKESTATIC demo/Target.fib(I)I
|
||||||
|
IADD
|
||||||
|
IRETURN
|
||||||
|
|
||||||
|
== invoke targets in the whole class ==
|
||||||
|
2 x demo/Target.fib
|
||||||
|
1 x indy:makeConcatWithConstants
|
||||||
|
1 x java/lang/IllegalStateException.<init>
|
||||||
|
1 x java/lang/Object.<init>
|
||||||
|
1 x java/lang/Thread.sleep
|
||||||
|
|
||||||
|
== a JDK class from the runtime image: java.lang.String ==
|
||||||
|
bytes 50116, major 69, methods 171, fields 11, interfaces 5
|
||||||
|
PASS Target.class is class-file version 69 (compiled with --release 25)
|
||||||
|
PASS Target has 8 methods (constructor + 7)
|
||||||
|
PASS fib calls itself twice
|
||||||
|
PASS greet() uses invokedynamic string concatenation
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.GenerateDemo target/gen/demo (25.0.5+8-LTS)
|
||||||
|
generated 501 bytes, major version 69 (wrote target/gen/demo/Generated.class)
|
||||||
|
ClassFile.verify(bytes) -> 0 problem(s)
|
||||||
|
PASS verify() finds nothing wrong with the generated class
|
||||||
|
defineClass -> demo.Generated hidden=false findable by name=true
|
||||||
|
[defineClass] add(2,3)=5 hello()=Hello from generated bytecode sumTo(100)=5050 classify(-4)=negative classify(4)=non-negative
|
||||||
|
PASS defineClass: generated methods return the right values
|
||||||
|
defineHiddenClass -> name starts with 'demo.Generated/': true hidden=true distinct from the normal class=true
|
||||||
|
[hidden] add(2,3)=5 hello()=Hello from generated bytecode sumTo(100)=5050 classify(-4)=negative classify(4)=non-negative
|
||||||
|
PASS hidden: generated methods return the right values
|
||||||
|
Class.forName(hidden name) -> ClassNotFoundException (hidden classes cannot be found by name)
|
||||||
|
PASS hidden class is hidden, the other is not
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
$ javap -c -p -v demo.Generated (the class GenerateDemo wrote; 25.0.5+8-LTS)
|
||||||
|
public class demo.Generated
|
||||||
|
minor version: 0
|
||||||
|
major version: 69
|
||||||
|
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
|
||||||
|
this_class: #2 // demo/Generated
|
||||||
|
super_class: #6 // java/lang/Object
|
||||||
|
interfaces: 0, fields: 0, methods: 5, attributes: 0
|
||||||
|
Constant pool:
|
||||||
|
#1 = Utf8 demo/Generated
|
||||||
|
#2 = Class #1 // demo/Generated
|
||||||
|
#3 = Utf8 <init>
|
||||||
|
#4 = Utf8 ()V
|
||||||
|
#5 = Utf8 java/lang/Object
|
||||||
|
#6 = Class #5 // java/lang/Object
|
||||||
|
#7 = NameAndType #3:#4 // "<init>":()V
|
||||||
|
#8 = Methodref #6.#7 // java/lang/Object."<init>":()V
|
||||||
|
#9 = Utf8 add
|
||||||
|
#10 = Utf8 (II)I
|
||||||
|
#11 = Utf8 hello
|
||||||
|
#12 = Utf8 ()Ljava/lang/String;
|
||||||
|
#13 = Utf8 Hello from generated bytecode
|
||||||
|
#14 = String #13 // Hello from generated bytecode
|
||||||
|
#15 = Utf8 sumTo
|
||||||
|
#16 = Utf8 (I)J
|
||||||
|
#17 = Utf8 classify
|
||||||
|
#18 = Utf8 (I)Ljava/lang/String;
|
||||||
|
#19 = Utf8 negative
|
||||||
|
#20 = String #19 // negative
|
||||||
|
#21 = Utf8 non-negative
|
||||||
|
#22 = String #21 // non-negative
|
||||||
|
#23 = Utf8 Code
|
||||||
|
#24 = Utf8 StackMapTable
|
||||||
|
#25 = Utf8 java/lang/String
|
||||||
|
#26 = Class #25 // java/lang/String
|
||||||
|
{
|
||||||
|
public demo.Generated();
|
||||||
|
descriptor: ()V
|
||||||
|
flags: (0x0001) ACC_PUBLIC
|
||||||
|
Code:
|
||||||
|
stack=1, locals=1, args_size=1
|
||||||
|
0: aload_0
|
||||||
|
1: invokespecial #8 // Method java/lang/Object."<init>":()V
|
||||||
|
4: return
|
||||||
|
|
||||||
|
public static int add(int, int);
|
||||||
|
descriptor: (II)I
|
||||||
|
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
|
||||||
|
Code:
|
||||||
|
stack=2, locals=2, args_size=2
|
||||||
|
0: iload_0
|
||||||
|
1: iload_1
|
||||||
|
2: iadd
|
||||||
|
3: ireturn
|
||||||
|
|
||||||
|
public static java.lang.String hello();
|
||||||
|
descriptor: ()Ljava/lang/String;
|
||||||
|
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
|
||||||
|
Code:
|
||||||
|
stack=1, locals=0, args_size=0
|
||||||
|
0: ldc #14 // String Hello from generated bytecode
|
||||||
|
2: areturn
|
||||||
|
|
||||||
|
public static long sumTo(int);
|
||||||
|
descriptor: (I)J
|
||||||
|
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
|
||||||
|
Code:
|
||||||
|
stack=4, locals=4, args_size=1
|
||||||
|
0: lconst_0
|
||||||
|
1: lstore_1
|
||||||
|
2: iconst_1
|
||||||
|
3: istore_3
|
||||||
|
4: iload_3
|
||||||
|
5: iload_0
|
||||||
|
6: if_icmpgt 20
|
||||||
|
9: lload_1
|
||||||
|
10: iload_3
|
||||||
|
11: i2l
|
||||||
|
12: ladd
|
||||||
|
13: lstore_1
|
||||||
|
14: iinc 3, 1
|
||||||
|
17: goto 4
|
||||||
|
20: lload_1
|
||||||
|
21: lreturn
|
||||||
|
StackMapTable: number_of_entries = 2
|
||||||
|
frame_type = 253 /* append */
|
||||||
|
offset_delta = 4
|
||||||
|
locals = [ long, int ]
|
||||||
|
frame_type = 15 /* same */
|
||||||
|
|
||||||
|
public static java.lang.String classify(int);
|
||||||
|
descriptor: (I)Ljava/lang/String;
|
||||||
|
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
|
||||||
|
Code:
|
||||||
|
stack=1, locals=1, args_size=1
|
||||||
|
0: iload_0
|
||||||
|
1: ifge 9
|
||||||
|
4: ldc #20 // String negative
|
||||||
|
6: goto 11
|
||||||
|
9: ldc #22 // String non-negative
|
||||||
|
11: areturn
|
||||||
|
StackMapTable: number_of_entries = 2
|
||||||
|
frame_type = 9 /* same */
|
||||||
|
frame_type = 65 /* same_locals_1_stack_item */
|
||||||
|
stack = [ class java/lang/String ]
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.BrokenGenerate (25.0.5+8-LTS)
|
||||||
|
DROP_STACK_MAPS: verify() -> 1 problem(s)
|
||||||
|
Expecting a stackmap frame at branch target 8 in demo/Broken::pick(int) @1
|
||||||
|
DROP_STACK_MAPS: defineClass -> java.lang.VerifyError
|
||||||
|
Expecting a stackmap frame at branch target 8
|
||||||
|
Exception Details:
|
||||||
|
Location:
|
||||||
|
PASS a branching method built without stack maps fails verification
|
||||||
|
PASS the same code with default options verifies
|
||||||
|
ireturn in a String method: build() succeeded (126 bytes)
|
||||||
|
verify: Bad return type in demo/Wrong::bad() @1 (java/lang/String is not assignable from integer_type)
|
||||||
|
PASS verify() catches a wrongly typed return
|
||||||
|
PASS stack underflow is caught while building
|
||||||
|
underflow: build() threw java.lang.IllegalArgumentException
|
||||||
|
Operand stack underflow at bytecode offset 0 of method u()
|
||||||
|
swapped labels: build() succeeded (173 bytes), verify() -> 0 problem(s)
|
||||||
|
swapped labels: defineClass -> java.lang.ClassFormatError: Illegal exception table range in class file demo/Swapped
|
||||||
|
PASS the JVM rejects the swapped exception-table labels
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.TransformDemo target/instrumented (25.0.5+8-LTS)
|
||||||
|
original 1488 bytes, naive 1799 bytes, with exception handler 2155 bytes
|
||||||
|
-- naive: time normal returns only (1799 bytes; verify() problems: 0)
|
||||||
|
PASS naive: time normal returns only: demo.Target here is a different Class object than the one on the class path
|
||||||
|
boom() threw java.lang.IllegalStateException: boom
|
||||||
|
explode() threw ArrayIndexOutOfBoundsException
|
||||||
|
fib recorded 177 call(s)
|
||||||
|
sumTo recorded 1 call(s)
|
||||||
|
greet recorded 1 call(s)
|
||||||
|
pause recorded 1 call(s)
|
||||||
|
boom recorded 0 call(s)
|
||||||
|
explode recorded 0 call(s)
|
||||||
|
PASS naive version never records the two methods that throw
|
||||||
|
PASS fib(10) makes 177 calls and 177 timings were recorded (recursion included)
|
||||||
|
-- full: also time when an exception leaves the method (2155 bytes; verify() problems: 0)
|
||||||
|
PASS full: also time when an exception leaves the method: demo.Target here is a different Class object than the one on the class path
|
||||||
|
boom() threw java.lang.IllegalStateException: boom
|
||||||
|
explode() threw ArrayIndexOutOfBoundsException
|
||||||
|
fib recorded 177 call(s)
|
||||||
|
sumTo recorded 1 call(s)
|
||||||
|
greet recorded 1 call(s)
|
||||||
|
pause recorded 1 call(s)
|
||||||
|
boom recorded 1 call(s)
|
||||||
|
explode recorded 1 call(s)
|
||||||
|
PASS exception-safe version records boom() and explode() once each
|
||||||
|
PASS fib still recorded 177 times
|
||||||
|
PASS sumTo and greet recorded once each
|
||||||
|
PASS pause(50) was recorded as at least 50 ms (>= 50,000,000 ns)
|
||||||
|
PASS fib(20) gives the same answer before and after
|
||||||
|
PASS sumTo(12345) gives the same answer before and after
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
$ javap -c -p demo.Target (original, as javac produced it; fib and boom only)
|
||||||
|
public static int fib(int);
|
||||||
|
Code:
|
||||||
|
0: iload_0
|
||||||
|
1: iconst_2
|
||||||
|
2: if_icmpge 9
|
||||||
|
5: iload_0
|
||||||
|
6: goto 22
|
||||||
|
9: iload_0
|
||||||
|
10: iconst_1
|
||||||
|
11: isub
|
||||||
|
12: invokestatic #13 // Method fib:(I)I
|
||||||
|
15: iload_0
|
||||||
|
16: iconst_2
|
||||||
|
17: isub
|
||||||
|
18: invokestatic #13 // Method fib:(I)I
|
||||||
|
21: iadd
|
||||||
|
22: ireturn
|
||||||
|
|
||||||
|
public static void boom();
|
||||||
|
Code:
|
||||||
|
0: new #31 // class java/lang/IllegalStateException
|
||||||
|
3: dup
|
||||||
|
4: ldc #33 // String boom
|
||||||
|
6: invokespecial #35 // Method java/lang/IllegalStateException."<init>":(Ljava/lang/String;)V
|
||||||
|
9: athrow
|
||||||
|
|
||||||
|
$ javap -c -p demo.Target (naive transform: records on normal return only)
|
||||||
|
public static int fib(int);
|
||||||
|
Code:
|
||||||
|
0: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
3: lstore_1
|
||||||
|
4: iload_0
|
||||||
|
5: iconst_2
|
||||||
|
6: if_icmpge 13
|
||||||
|
9: iload_0
|
||||||
|
10: goto 26
|
||||||
|
13: iload_0
|
||||||
|
14: iconst_1
|
||||||
|
15: isub
|
||||||
|
16: invokestatic #13 // Method fib:(I)I
|
||||||
|
19: iload_0
|
||||||
|
20: iconst_2
|
||||||
|
21: isub
|
||||||
|
22: invokestatic #13 // Method fib:(I)I
|
||||||
|
25: iadd
|
||||||
|
26: ldc #76 // String Target.fib
|
||||||
|
28: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
31: lload_1
|
||||||
|
32: lsub
|
||||||
|
33: invokestatic #82 // Method demo/Timings.record:(Ljava/lang/String;J)V
|
||||||
|
36: ireturn
|
||||||
|
|
||||||
|
public static void boom();
|
||||||
|
Code:
|
||||||
|
0: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
3: lstore_0
|
||||||
|
4: new #31 // class java/lang/IllegalStateException
|
||||||
|
7: dup
|
||||||
|
8: ldc #33 // String boom
|
||||||
|
10: invokespecial #35 // Method java/lang/IllegalStateException."<init>":(Ljava/lang/String;)V
|
||||||
|
13: athrow
|
||||||
|
|
||||||
|
$ javap -c -p demo.Target (full transform: plus a catch-all handler)
|
||||||
|
public static int fib(int);
|
||||||
|
Code:
|
||||||
|
0: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
3: lstore_1
|
||||||
|
4: iload_0
|
||||||
|
5: iconst_2
|
||||||
|
6: if_icmpge 13
|
||||||
|
9: iload_0
|
||||||
|
10: goto 26
|
||||||
|
13: iload_0
|
||||||
|
14: iconst_1
|
||||||
|
15: isub
|
||||||
|
16: invokestatic #13 // Method fib:(I)I
|
||||||
|
19: iload_0
|
||||||
|
20: iconst_2
|
||||||
|
21: isub
|
||||||
|
22: invokestatic #13 // Method fib:(I)I
|
||||||
|
25: iadd
|
||||||
|
26: ldc #76 // String Target.fib
|
||||||
|
28: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
31: lload_1
|
||||||
|
32: lsub
|
||||||
|
33: invokestatic #82 // Method demo/Timings.record:(Ljava/lang/String;J)V
|
||||||
|
36: ireturn
|
||||||
|
37: astore_3
|
||||||
|
38: ldc #76 // String Target.fib
|
||||||
|
40: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
43: lload_1
|
||||||
|
44: lsub
|
||||||
|
45: invokestatic #82 // Method demo/Timings.record:(Ljava/lang/String;J)V
|
||||||
|
48: aload_3
|
||||||
|
49: athrow
|
||||||
|
Exception table:
|
||||||
|
from to target type
|
||||||
|
4 37 37 any
|
||||||
|
|
||||||
|
public static void boom();
|
||||||
|
Code:
|
||||||
|
0: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
3: lstore_0
|
||||||
|
4: new #31 // class java/lang/IllegalStateException
|
||||||
|
7: dup
|
||||||
|
8: ldc #33 // String boom
|
||||||
|
10: invokespecial #35 // Method java/lang/IllegalStateException."<init>":(Ljava/lang/String;)V
|
||||||
|
13: athrow
|
||||||
|
14: astore_2
|
||||||
|
15: ldc #90 // String Target.boom
|
||||||
|
17: invokestatic #74 // Method java/lang/System.nanoTime:()J
|
||||||
|
20: lload_0
|
||||||
|
21: lsub
|
||||||
|
22: invokestatic #82 // Method demo/Timings.record:(Ljava/lang/String;J)V
|
||||||
|
25: aload_2
|
||||||
|
26: athrow
|
||||||
|
Exception table:
|
||||||
|
from to target type
|
||||||
|
4 14 14 any
|
||||||
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
$ javap -public java.lang.classfile.** on each JDK, then diff by class (24: OpenJDK Runtime Environment Temurin-24.0.2+12 (build 24.0.2+12), 26: OpenJDK Runtime Environment Temurin-26.0.2.1+1 (build 26.0.2.1+1))
|
||||||
|
|
||||||
|
=== JDK 24 -> JDK 25 ===
|
||||||
|
+ java.lang.classfile.ClassFile: public static final int JAVA_25_VERSION;
|
||||||
|
~ java.lang.classfile.attribute.UnknownAttribute
|
||||||
|
was: public interface java.lang.classfile.attribute.UnknownAttribute extends java.lang.classfile.Attribute<java.lang.classfile.attribute.UnknownAttribute>, java.lang.classfile.ClassElement, java.lang.classfile.MethodElement, java.lang.classfile.FieldElement {
|
||||||
|
now: public interface java.lang.classfile.attribute.UnknownAttribute extends java.lang.classfile.Attribute<java.lang.classfile.attribute.UnknownAttribute>, java.lang.classfile.ClassElement, java.lang.classfile.MethodElement, java.lang.classfile.FieldElement, java.lang.classfile.CodeElement {
|
||||||
|
+ java.lang.classfile.constantpool.ClassEntry: public abstract boolean matches(java.lang.constant.ClassDesc);
|
||||||
|
+ java.lang.classfile.constantpool.MethodTypeEntry: public abstract boolean matches(java.lang.constant.MethodTypeDesc);
|
||||||
|
+ java.lang.classfile.constantpool.ModuleEntry: public abstract boolean matches(java.lang.constant.ModuleDesc);
|
||||||
|
+ java.lang.classfile.constantpool.PackageEntry: public abstract boolean matches(java.lang.constant.PackageDesc);
|
||||||
|
+ java.lang.classfile.constantpool.StringEntry: public abstract boolean equalsString(java.lang.String);
|
||||||
|
+ java.lang.classfile.constantpool.Utf8Entry: public abstract boolean isFieldType(java.lang.constant.ClassDesc);
|
||||||
|
+ java.lang.classfile.constantpool.Utf8Entry: public abstract boolean isMethodType(java.lang.constant.MethodTypeDesc);
|
||||||
|
239 classes in old, 239 in new, 9 difference(s)
|
||||||
|
|
||||||
|
=== JDK 25 -> JDK 26 ===
|
||||||
|
+ java.lang.classfile.ClassFile: public static final int JAVA_26_VERSION;
|
||||||
|
239 classes in old, 239 in new, 1 difference(s)
|
||||||
|
|
||||||
|
=== is it a preview API on JDK 24? ===
|
||||||
|
$ javap -v java.lang.classfile.ClassFile | grep -ci PreviewFeature
|
||||||
|
24.0.2+12: 0
|
||||||
|
25.0.5+8-LTS: 0
|
||||||
|
26.0.2.1+1: 0
|
||||||
|
|
||||||
|
=== @since of ClassFile ===
|
||||||
|
jdk-24.0.2+12: * @since 24
|
||||||
|
jdk-25.0.5+8: * @since 24
|
||||||
|
jdk-26.0.2.1+1: * @since 24
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.AsmParse (25.0.5+8-LTS)
|
||||||
|
ASM sees major version 69
|
||||||
|
public <init>(Ljava/lang/String;)V
|
||||||
|
public,static fib(I)I
|
||||||
|
public,static sumTo(I)J
|
||||||
|
public greet(Ljava/lang/String;)Ljava/lang/String;
|
||||||
|
public pause(J)V
|
||||||
|
public,static boom()V
|
||||||
|
public,static explode([I)I
|
||||||
|
public calls()I
|
||||||
|
2 x demo/Target.fib
|
||||||
|
1 x indy:makeConcatWithConstants
|
||||||
|
1 x java/lang/IllegalStateException.<init>
|
||||||
|
1 x java/lang/Object.<init>
|
||||||
|
1 x java/lang/Thread.sleep
|
||||||
|
PASS ASM and java.lang.classfile list identical method lines
|
||||||
|
PASS ASM and java.lang.classfile count identical invoke targets
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.AsmGenerate (25.0.5+8-LTS)
|
||||||
|
ASM generated 501 bytes; java.lang.classfile generated 501 bytes
|
||||||
|
PASS ASM output passes ClassFile.verify()
|
||||||
|
[ASM-generated] add(2,3)=5 hello()=Hello from generated bytecode sumTo(100)=5050 classify(-4)=negative classify(4)=non-negative
|
||||||
|
PASS ASM-generated: generated methods return the right values
|
||||||
|
PASS both generators emit the same method list
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.AsmInstrument (25.0.5+8-LTS)
|
||||||
|
original 1488 bytes, ASM-instrumented 2152 bytes
|
||||||
|
PASS ASM output passes ClassFile.verify()
|
||||||
|
-- ASM AdviceAdapter version (2152 bytes; verify() problems: 0)
|
||||||
|
PASS ASM AdviceAdapter version: demo.Target here is a different Class object than the one on the class path
|
||||||
|
boom() threw java.lang.IllegalStateException: boom
|
||||||
|
explode() threw ArrayIndexOutOfBoundsException
|
||||||
|
fib recorded 177 call(s)
|
||||||
|
sumTo recorded 1 call(s)
|
||||||
|
greet recorded 1 call(s)
|
||||||
|
pause recorded 1 call(s)
|
||||||
|
boom recorded 1 call(s)
|
||||||
|
explode recorded 1 call(s)
|
||||||
|
PASS ASM version also records both throwing methods once
|
||||||
|
PASS ASM version: fib recorded 177 times
|
||||||
|
PASS ASM version: pause(50) recorded as at least 50 ms
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.VersionLimits (25.0.5+8-LTS)
|
||||||
|
running on Java 25; ClassFile.latestMajorVersion() = 69; ASM Opcodes.V25=69, V28=72
|
||||||
|
major 69:
|
||||||
|
java.lang.classfile : parsed, 8 methods
|
||||||
|
ASM 9.11.1 : parsed, 8 methods
|
||||||
|
major 70:
|
||||||
|
java.lang.classfile : java.lang.IllegalArgumentException: Unsupported class file version: 70
|
||||||
|
ASM 9.11.1 : parsed, 8 methods
|
||||||
|
major 72:
|
||||||
|
java.lang.classfile : java.lang.IllegalArgumentException: Unsupported class file version: 72
|
||||||
|
ASM 9.11.1 : parsed, 8 methods
|
||||||
|
major 73:
|
||||||
|
java.lang.classfile : java.lang.IllegalArgumentException: Unsupported class file version: 73
|
||||||
|
ASM 9.11.1 : java.lang.IllegalArgumentException: Unsupported class file version 73.0
|
||||||
|
major 99:
|
||||||
|
java.lang.classfile : java.lang.IllegalArgumentException: Unsupported class file version: 99
|
||||||
|
ASM 9.11.1 : java.lang.IllegalArgumentException: Unsupported class file version 99.0
|
||||||
|
PASS major 69 parses with java.lang.classfile
|
||||||
|
PASS one version above the JDK's own is rejected by java.lang.classfile
|
||||||
|
PASS ASM 9.11.1 still reads major 72 (Java 28)
|
||||||
|
PASS ASM 9.11.1 rejects major 73
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
Lines of code in the method(s) that do the job (non-blank, non-comment), counted by scripts/run-all.sh:
|
||||||
|
generate demo.Generated java.lang.classfile 32 ASM 63
|
||||||
|
timing instrumentation java.lang.classfile 61 ASM 43
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
--- run 1 of 3 ---
|
||||||
|
running on Java 25.0.5+8-LTS, ASM 9.11.1; INDICATIVE numbers, thread CPU time, shared 2-vCPU sandbox, no JMH
|
||||||
|
2000 classes from java.base, 7001 KiB; 4 warm-up rounds, median of 9
|
||||||
|
instructions seen: java.lang.classfile 478741, ASM 478741
|
||||||
|
parse + visit every instruction : java.lang.classfile 119.4 ms ASM 166.1 ms (ASM / classfile = 1.39)
|
||||||
|
parse + copy + write back : java.lang.classfile 38.6 ms ASM 78.9 ms (ASM / classfile = 2.05)
|
||||||
|
--- run 2 of 3 ---
|
||||||
|
running on Java 25.0.5+8-LTS, ASM 9.11.1; INDICATIVE numbers, thread CPU time, shared 2-vCPU sandbox, no JMH
|
||||||
|
2000 classes from java.base, 7001 KiB; 4 warm-up rounds, median of 9
|
||||||
|
instructions seen: java.lang.classfile 478741, ASM 478741
|
||||||
|
parse + visit every instruction : java.lang.classfile 63.9 ms ASM 166.2 ms (ASM / classfile = 2.60)
|
||||||
|
parse + copy + write back : java.lang.classfile 26.8 ms ASM 88.1 ms (ASM / classfile = 3.29)
|
||||||
|
--- run 3 of 3 ---
|
||||||
|
running on Java 25.0.5+8-LTS, ASM 9.11.1; INDICATIVE numbers, thread CPU time, shared 2-vCPU sandbox, no JMH
|
||||||
|
2000 classes from java.base, 7001 KiB; 4 warm-up rounds, median of 9
|
||||||
|
instructions seen: java.lang.classfile 478741, ASM 478741
|
||||||
|
parse + visit every instruction : java.lang.classfile 48.8 ms ASM 44.2 ms (ASM / classfile = 0.90)
|
||||||
|
parse + copy + write back : java.lang.classfile 18.8 ms ASM 101.6 ms (ASM / classfile = 5.39)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
$ unzip -l spring-core-7.0.10.jar | grep 'META-INF/versions/24/.*\.class' | wc -l
|
||||||
|
9
|
||||||
|
|
||||||
|
$ unzip -l spring-core-7.0.10.jar | grep 'versions/24.*ClassFile'
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileAnnotationDelegate$Source.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileAnnotationDelegate.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileAnnotationMetadata$Builder.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileAnnotationMetadata.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileMetadataReader.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileMetadataReaderFactory.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileMethodMetadata$Source.class
|
||||||
|
META-INF/versions/24/org/springframework/core/type/classreading/ClassFileMethodMetadata.class
|
||||||
|
|
||||||
|
$ unzip -l spring-core-7.0.10.jar | grep -c 'org/springframework/asm/.*\.class' (the repackaged ASM is still there)
|
||||||
|
37
|
||||||
|
|
||||||
|
$ javap -v -cp <jar>!/META-INF/versions/24 ...ClassFileMetadataReader | grep java/lang/classfile (does it really call the JDK API?)
|
||||||
|
java/lang/classfile/ClassFile
|
||||||
|
java/lang/classfile/ClassModel
|
||||||
|
|
||||||
|
$ unzip -p spring-core-7.0.10.jar META-INF/MANIFEST.MF | grep -i multi-release
|
||||||
|
Multi-Release: true
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
$ java -cp classes:asm-9.11.1.jar... demo.AsmGotcha (25.0.5+8-LTS)
|
||||||
|
readerFlags = 0 -> java.lang.IllegalArgumentException
|
||||||
|
LocalVariablesSorter only accepts expanded frames (see ClassReader.EXPAND_FRAMES)
|
||||||
|
PASS the message names the missing flag
|
||||||
|
readerFlags = EXPAND_FRAMES -> 2152 bytes, verify() problems: 0
|
||||||
|
PASS with EXPAND_FRAMES the output verifies
|
||||||
|
exit=0
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.ankurm.javademos</groupId>
|
||||||
|
<artifactId>classfile-api</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>classfile-api</name>
|
||||||
|
<description>java.lang.classfile (JEP 484, final in JDK 24): read, generate and transform bytecode, compared with ASM</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<asm.version>9.11.1</asm.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- ASM is used ONLY by the comparison classes (Asm*.java) and Bench; the java.lang.classfile demos need no dependency. -->
|
||||||
|
<dependency><groupId>org.ow2.asm</groupId><artifactId>asm</artifactId><version>${asm.version}</version></dependency>
|
||||||
|
<dependency><groupId>org.ow2.asm</groupId><artifactId>asm-commons</artifactId><version>${asm.version}</version></dependency>
|
||||||
|
<dependency><groupId>org.ow2.asm</groupId><artifactId>asm-util</artifactId><version>${asm.version}</version></dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.13.0</version>
|
||||||
|
<configuration><compilerArgs><arg>-Xlint:all</arg></compilerArgs></configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<version>3.8.1</version>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Owner-aware diff of two `javap -public` dumps (one per JDK). Usage: api_diff.py OLD.txt NEW.txt"""
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def load(p):
|
||||||
|
cur, d = None, {}
|
||||||
|
for line in open(p):
|
||||||
|
line = line.rstrip("\n")
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
if not line.startswith(" "):
|
||||||
|
cur = line.rstrip(" {").split(" extends ")[0].split(" implements ")[0].rsplit(" ", 1)[-1]
|
||||||
|
d[cur] = {"__header__": line}
|
||||||
|
elif line.strip() != "}":
|
||||||
|
d[cur][line.strip()] = True
|
||||||
|
return d
|
||||||
|
|
||||||
|
a, b = load(sys.argv[1]), load(sys.argv[2])
|
||||||
|
changes = 0
|
||||||
|
for c in sorted(set(a) | set(b)):
|
||||||
|
if c not in a: print(f"+ class {c}"); changes += 1; continue
|
||||||
|
if c not in b: print(f"- class {c}"); changes += 1; continue
|
||||||
|
if a[c]["__header__"] != b[c]["__header__"]:
|
||||||
|
print(f"~ {c}\n was: {a[c]['__header__']}\n now: {b[c]['__header__']}"); changes += 1
|
||||||
|
for m in sorted(set(a[c]) - set(b[c]) - {"__header__"}): print(f"- {c}: {m}"); changes += 1
|
||||||
|
for m in sorted(set(b[c]) - set(a[c]) - {"__header__"}): print(f"+ {c}: {m}"); changes += 1
|
||||||
|
print(f"{len(a)} classes in old, {len(b)} in new, {changes} difference(s)")
|
||||||
Executable
+84
@@ -0,0 +1,84 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# classfile-api: regenerates every file in output/.
|
||||||
|
# JDK25=/path/to/jdk-25 [JDK24=/path/to/jdk-24 JDK26=/path/to/jdk-26] ./scripts/run-all.sh
|
||||||
|
# Needs Maven (or an existing target/lib with the ASM jars) for the ASM comparison. JDK24/JDK26 are optional: output/07 is skipped without them.
|
||||||
|
set -uo pipefail
|
||||||
|
HERE="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
cd "$HERE"
|
||||||
|
JDK25="${JDK25:-/opt/jdks/jdk-25.0.5+8}"
|
||||||
|
J="$JDK25/bin"
|
||||||
|
OUT="$HERE/output"; mkdir -p "$OUT"
|
||||||
|
CP="target/c:target/lib/*"
|
||||||
|
JV="$("$J/java" -version 2>&1 | grep -v '^Picked' | sed -n 2p | sed 's/.*(build \(.*\))/\1/')"
|
||||||
|
|
||||||
|
# 1. ASM jars (the only dependency) and compile. Unsetting JAVA_TOOL_OPTIONS keeps proxy banners out of the transcripts.
|
||||||
|
if [ ! -d target/lib ]; then
|
||||||
|
JAVA_HOME="$JDK25" mvn -B -q -T1 dependency:copy-dependencies -DoutputDirectory=target/lib || exit 1
|
||||||
|
fi
|
||||||
|
unset JAVA_TOOL_OPTIONS
|
||||||
|
rm -rf target/c target/gen target/instrumented; mkdir -p target/c
|
||||||
|
echo "javac: $("$J/javac" -version 2>&1)"
|
||||||
|
"$J/javac" --release 25 -Xlint:all -cp "target/lib/*" -d target/c src/main/java/demo/*.java || exit 1
|
||||||
|
|
||||||
|
run() { # run <outfile> <main class> [args] -- prints the command, then the output, then the exit code
|
||||||
|
local f="$1"; shift
|
||||||
|
{ echo "\$ java -cp classes:asm-9.11.1.jar... $* ($JV)"; "$J/java" -Xmx512m -cp "$CP" "$@" 2>&1; echo "exit=$?"; } > "$OUT/$f"
|
||||||
|
}
|
||||||
|
|
||||||
|
run 01-parse.txt demo.ParseDemo
|
||||||
|
run 02-generate.txt demo.GenerateDemo target/gen/demo
|
||||||
|
{ echo "\$ javap -c -p -v demo.Generated (the class GenerateDemo wrote; $JV)"
|
||||||
|
"$J/javap" -c -p -v -cp target/gen demo.Generated 2>&1 | grep -v -e '^Classfile ' -e '^ Last modified' -e '^ SHA-256'; } > "$OUT/03-javap-generated.txt"
|
||||||
|
run 04-broken-generate.txt demo.BrokenGenerate
|
||||||
|
run 05-transform.txt demo.TransformDemo target/instrumented
|
||||||
|
meth() { awk -v pat="$1" '$0 ~ pat {f=1} f{print} f && /^$/ {f=0}'; } # one method block of javap -c output
|
||||||
|
{ echo "\$ javap -c -p demo.Target (original, as javac produced it; fib and boom only)"
|
||||||
|
"$J/javap" -c -p -cp target/c demo.Target | meth 'static int fib'
|
||||||
|
"$J/javap" -c -p -cp target/c demo.Target | meth 'static void boom'
|
||||||
|
echo "\$ javap -c -p demo.Target (naive transform: records on normal return only)"
|
||||||
|
"$J/javap" -c -p -cp target/instrumented/naive demo.Target | meth 'static int fib'
|
||||||
|
"$J/javap" -c -p -cp target/instrumented/naive demo.Target | meth 'static void boom'
|
||||||
|
echo "\$ javap -c -p demo.Target (full transform: plus a catch-all handler)"
|
||||||
|
"$J/javap" -c -p -cp target/instrumented/full demo.Target | meth 'static int fib'
|
||||||
|
"$J/javap" -c -p -cp target/instrumented/full demo.Target | meth 'static void boom'
|
||||||
|
} > "$OUT/06-javap-instrumented.txt"
|
||||||
|
|
||||||
|
# 2. ASM comparison, same tasks
|
||||||
|
run 08-asm-parse.txt demo.AsmParse
|
||||||
|
run 09-asm-generate.txt demo.AsmGenerate
|
||||||
|
run 10-asm-instrument.txt demo.AsmInstrument
|
||||||
|
run 15-asm-expand-frames.txt demo.AsmGotcha
|
||||||
|
run 11-version-limits.txt demo.VersionLimits
|
||||||
|
# size of the equivalent code, counting only the method(s) that do the job (non-blank, non-comment lines)
|
||||||
|
body() { awk -v pat="$2" '$0 ~ pat {f=1} f && !/^[[:space:]]*(\/\/|\*|\/\*|$)/ {n++} f && /^ }$/ {f=0} END {print n+0}' "$1"; }
|
||||||
|
{ echo "Lines of code in the method(s) that do the job (non-blank, non-comment), counted by scripts/run-all.sh:"
|
||||||
|
printf "%-26s java.lang.classfile %3d ASM %3d\n" "generate demo.Generated" "$(body src/main/java/demo/GenerateDemo.java 'static byte\[\] generate')" "$(body src/main/java/demo/AsmGenerate.java 'static byte\[\] generate')"
|
||||||
|
printf "%-26s java.lang.classfile %3d ASM %3d\n" "timing instrumentation" "$(( $(body src/main/java/demo/TimingTransform.java 'public static byte\[\] instrument') + $(body src/main/java/demo/TimingTransform.java 'private static final class Timer') ))" "$(body src/main/java/demo/AsmInstrument.java 'public static byte\[\] instrument')"
|
||||||
|
} > "$OUT/12-line-counts.txt"
|
||||||
|
# Bench: three separate JVMs, because a single run on a shared machine is not trustworthy
|
||||||
|
if [ -z "${SKIP_BENCH:-}" ]; then
|
||||||
|
{ for i in 1 2 3; do echo "--- run $i of 3 ---"; "$J/java" -Xmx512m -cp "$CP" demo.Bench 2>&1 | grep -v '^PASS'; done; } > "$OUT/13-bench.txt"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Public API of java.lang.classfile across JDK 24, 25, 26 (needs the other JDKs)
|
||||||
|
if [ -n "${JDK24:-}" ] && [ -n "${JDK26:-}" ]; then
|
||||||
|
api() { # api <jdk-home> <outfile>
|
||||||
|
local classes
|
||||||
|
classes=$("$1/bin/jimage" list "$1/lib/modules" | awk '/^Module: java.base/{f=1;next} /^Module:/{f=0} f' \
|
||||||
|
| grep -E 'java/lang/classfile/.*\.class$' | grep -v -e package-info -e Snippets | sed 's/\.class$//;s#/#.#g;s/^ *//')
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
"$1/bin/javap" -public -cp none $classes 2>/dev/null | grep -v '^Compiled from' > "$2"
|
||||||
|
}
|
||||||
|
T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT
|
||||||
|
api "$JDK24" "$T/24.txt"; api "$JDK25" "$T/25.txt"; api "$JDK26" "$T/26.txt"
|
||||||
|
{ echo "\$ javap -public java.lang.classfile.** on each JDK, then diff by class (24: $("$JDK24/bin/java" -version 2>&1 | grep -v '^Picked' | sed -n 2p), 26: $("$JDK26/bin/java" -version 2>&1 | grep -v '^Picked' | sed -n 2p))"
|
||||||
|
echo; echo "=== JDK 24 -> JDK 25 ==="; python3 -I scripts/api_diff.py "$T/24.txt" "$T/25.txt"
|
||||||
|
echo; echo "=== JDK 25 -> JDK 26 ==="; python3 -I scripts/api_diff.py "$T/25.txt" "$T/26.txt"
|
||||||
|
echo; echo "=== is it a preview API on JDK 24? ==="; echo "\$ javap -v java.lang.classfile.ClassFile | grep -ci PreviewFeature"
|
||||||
|
for j in "$JDK24" "$JDK25" "$JDK26"; do echo "$("$j/bin/java" -version 2>&1 | grep -v '^Picked' | sed -n 2p | sed 's/.*(build \(.*\))/\1/'): $("$j/bin/javap" -v java.lang.classfile.ClassFile | grep -ci PreviewFeature)"; done
|
||||||
|
echo; echo "=== @since of ClassFile ==="; for j in "$JDK24" "$JDK25" "$JDK26"; do unzip -p "$j/lib/src.zip" java.base/java/lang/classfile/ClassFile.java | grep -m1 '@since' | sed "s|^|$(basename "$j"): |"; done
|
||||||
|
} > "$OUT/07-api-diff-24-25-26.txt"
|
||||||
|
else
|
||||||
|
echo "JDK24/JDK26 not set: skipped output/07-api-diff-24-25-26.txt"
|
||||||
|
fi
|
||||||
|
echo done
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Who is migrating? Look inside spring-core's published jar instead of trusting a blog.
|
||||||
|
# JDK25=/path/to/jdk-25 ./scripts/spring-core-probe.sh [spring-core-version] -> output/14-spring-core-probe.txt
|
||||||
|
set -uo pipefail
|
||||||
|
unset JAVA_TOOL_OPTIONS
|
||||||
|
HERE="$(cd "$(dirname "$0")/.." && pwd)"; JDK25="${JDK25:-/opt/jdks/jdk-25.0.5+8}"; V="${1:-7.0.10}"
|
||||||
|
W="$(mktemp -d)"; trap 'rm -rf "$W"' EXIT
|
||||||
|
URL="https://repo1.maven.org/maven2/org/springframework/spring-core/$V/spring-core-$V.jar"
|
||||||
|
for i in 1 2 3 4 5 6; do c=$(curl -s -o "$W/sc.jar" -w '%{http_code}' "$URL"); [ "$c" = 200 ] && break; sleep 20; done
|
||||||
|
[ "$c" = 200 ] || { echo "download failed ($c)"; exit 1; }
|
||||||
|
{
|
||||||
|
echo "\$ unzip -l spring-core-$V.jar | grep 'META-INF/versions/24/.*\\.class' | wc -l"
|
||||||
|
unzip -l "$W/sc.jar" | grep -E 'META-INF/versions/24/.*\.class' | wc -l
|
||||||
|
echo; echo "\$ unzip -l spring-core-$V.jar | grep 'versions/24.*ClassFile'"
|
||||||
|
unzip -l "$W/sc.jar" | grep -E 'versions/24/.*ClassFile' | awk '{print $4}'
|
||||||
|
echo; echo "\$ unzip -l spring-core-$V.jar | grep -c 'org/springframework/asm/.*\\.class' (the repackaged ASM is still there)"
|
||||||
|
unzip -l "$W/sc.jar" | grep -cE 'org/springframework/asm/.*\.class'
|
||||||
|
echo; echo "\$ javap -v -cp <jar>!/META-INF/versions/24 ...ClassFileMetadataReader | grep java/lang/classfile (does it really call the JDK API?)"
|
||||||
|
mkdir "$W/x"; unzip -q "$W/sc.jar" 'META-INF/versions/24/org/springframework/core/type/classreading/ClassFileMetadataReader*' -d "$W/x"
|
||||||
|
"$JDK25/bin/javap" -v -cp "$W/x/META-INF/versions/24" org.springframework.core.type.classreading.ClassFileMetadataReader | grep -o 'java/lang/classfile/[A-Za-z$/]*' | sort -u
|
||||||
|
echo; echo "\$ unzip -p spring-core-$V.jar META-INF/MANIFEST.MF | grep -i multi-release"
|
||||||
|
unzip -p "$W/sc.jar" META-INF/MANIFEST.MF | grep -i multi-release
|
||||||
|
} > "$HERE/output/14-spring-core-probe.txt" 2>&1
|
||||||
|
cat "$HERE/output/14-spring-core-probe.txt"
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Label;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
|
||||||
|
/** The GenerateDemo task done with ASM 9.11.1: the same class, demo.Generated, same four methods. */
|
||||||
|
public class AsmGenerate implements Opcodes {
|
||||||
|
|
||||||
|
static byte[] generate() {
|
||||||
|
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
||||||
|
cw.visit(V25, ACC_PUBLIC | ACC_SUPER, "demo/Generated", null, "java/lang/Object", null);
|
||||||
|
|
||||||
|
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||||
|
mv.visitCode();
|
||||||
|
mv.visitVarInsn(ALOAD, 0);
|
||||||
|
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||||
|
mv.visitInsn(RETURN);
|
||||||
|
mv.visitMaxs(0, 0);
|
||||||
|
mv.visitEnd();
|
||||||
|
|
||||||
|
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", null, null);
|
||||||
|
mv.visitCode();
|
||||||
|
mv.visitVarInsn(ILOAD, 0);
|
||||||
|
mv.visitVarInsn(ILOAD, 1);
|
||||||
|
mv.visitInsn(IADD);
|
||||||
|
mv.visitInsn(IRETURN);
|
||||||
|
mv.visitMaxs(0, 0);
|
||||||
|
mv.visitEnd();
|
||||||
|
|
||||||
|
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "hello", "()Ljava/lang/String;", null, null);
|
||||||
|
mv.visitCode();
|
||||||
|
mv.visitLdcInsn("Hello from generated bytecode");
|
||||||
|
mv.visitInsn(ARETURN);
|
||||||
|
mv.visitMaxs(0, 0);
|
||||||
|
mv.visitEnd();
|
||||||
|
|
||||||
|
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "sumTo", "(I)J", null, null);
|
||||||
|
mv.visitCode();
|
||||||
|
Label loop = new Label(), end = new Label();
|
||||||
|
mv.visitInsn(LCONST_0);
|
||||||
|
mv.visitVarInsn(LSTORE, 1);
|
||||||
|
mv.visitInsn(ICONST_1);
|
||||||
|
mv.visitVarInsn(ISTORE, 3);
|
||||||
|
mv.visitLabel(loop);
|
||||||
|
mv.visitVarInsn(ILOAD, 3);
|
||||||
|
mv.visitVarInsn(ILOAD, 0);
|
||||||
|
mv.visitJumpInsn(IF_ICMPGT, end);
|
||||||
|
mv.visitVarInsn(LLOAD, 1);
|
||||||
|
mv.visitVarInsn(ILOAD, 3);
|
||||||
|
mv.visitInsn(I2L);
|
||||||
|
mv.visitInsn(LADD);
|
||||||
|
mv.visitVarInsn(LSTORE, 1);
|
||||||
|
mv.visitIincInsn(3, 1);
|
||||||
|
mv.visitJumpInsn(GOTO, loop);
|
||||||
|
mv.visitLabel(end);
|
||||||
|
mv.visitVarInsn(LLOAD, 1);
|
||||||
|
mv.visitInsn(LRETURN);
|
||||||
|
mv.visitMaxs(0, 0);
|
||||||
|
mv.visitEnd();
|
||||||
|
|
||||||
|
mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "classify", "(I)Ljava/lang/String;", null, null);
|
||||||
|
mv.visitCode();
|
||||||
|
Label nonNeg = new Label(), done = new Label();
|
||||||
|
mv.visitVarInsn(ILOAD, 0);
|
||||||
|
mv.visitJumpInsn(IFGE, nonNeg);
|
||||||
|
mv.visitLdcInsn("negative");
|
||||||
|
mv.visitJumpInsn(GOTO, done);
|
||||||
|
mv.visitLabel(nonNeg);
|
||||||
|
mv.visitLdcInsn("non-negative");
|
||||||
|
mv.visitLabel(done);
|
||||||
|
mv.visitInsn(ARETURN);
|
||||||
|
mv.visitMaxs(0, 0);
|
||||||
|
mv.visitEnd();
|
||||||
|
|
||||||
|
cw.visitEnd();
|
||||||
|
return cw.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Throwable {
|
||||||
|
byte[] asm = generate();
|
||||||
|
byte[] cfApi = GenerateDemo.generate(java.lang.classfile.ClassFile.of());
|
||||||
|
System.out.println("ASM generated " + asm.length + " bytes; java.lang.classfile generated " + cfApi.length + " bytes");
|
||||||
|
Check.that(java.lang.classfile.ClassFile.of().verify(asm).isEmpty(), "ASM output passes ClassFile.verify()");
|
||||||
|
Class<?> c = MethodHandles.lookup().defineClass(asm);
|
||||||
|
GenerateDemo.exercise(c, "ASM-generated");
|
||||||
|
var a = java.lang.classfile.ClassFile.of().parse(asm);
|
||||||
|
var b = java.lang.classfile.ClassFile.of().parse(cfApi);
|
||||||
|
Check.that(ParseDemo.methodLines(a).equals(ParseDemo.methodLines(b)), "both generators emit the same method list");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
/** The first thing that went wrong writing the ASM version: AdviceAdapter without ClassReader.EXPAND_FRAMES. */
|
||||||
|
public class AsmGotcha {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AsmInstrument.readerFlags = 0; // what you get if you copy a ClassVisitor example and pass 0
|
||||||
|
try {
|
||||||
|
AsmInstrument.instrument(Bytes.of(Target.class));
|
||||||
|
Check.that(false, "AdviceAdapter without EXPAND_FRAMES should have thrown");
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
System.out.println("readerFlags = 0 -> " + e.getClass().getName());
|
||||||
|
System.out.println(" " + e.getMessage());
|
||||||
|
Check.that(e.getMessage().contains("EXPAND_FRAMES"), "the message names the missing flag");
|
||||||
|
}
|
||||||
|
AsmInstrument.readerFlags = org.objectweb.asm.ClassReader.EXPAND_FRAMES;
|
||||||
|
byte[] ok = AsmInstrument.instrument(Bytes.of(Target.class));
|
||||||
|
System.out.println("readerFlags = EXPAND_FRAMES -> " + ok.length + " bytes, verify() problems: " + java.lang.classfile.ClassFile.of().verify(ok).size());
|
||||||
|
Check.that(java.lang.classfile.ClassFile.of().verify(ok).isEmpty(), "with EXPAND_FRAMES the output verifies");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Label;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.commons.AdviceAdapter;
|
||||||
|
|
||||||
|
/** The TimingTransform task done with ASM 9.11.1 (AdviceAdapter from asm-commons): same semantics as the "full" ClassFile version. */
|
||||||
|
public class AsmInstrument {
|
||||||
|
static int readerFlags = ClassReader.EXPAND_FRAMES; // AdviceAdapter extends LocalVariablesSorter, which throws without it
|
||||||
|
|
||||||
|
public static byte[] instrument(byte[] original) {
|
||||||
|
ClassReader cr = new ClassReader(original);
|
||||||
|
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
|
||||||
|
String simple = cr.getClassName().substring(cr.getClassName().lastIndexOf('/') + 1);
|
||||||
|
cr.accept(new ClassVisitor(Opcodes.ASM9, cw) {
|
||||||
|
@Override public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] ex) {
|
||||||
|
MethodVisitor mv = super.visitMethod(access, name, desc, sig, ex);
|
||||||
|
if (name.equals("<init>") || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) return mv;
|
||||||
|
return new AdviceAdapter(Opcodes.ASM9, mv, access, name, desc) {
|
||||||
|
final Label tryStart = new Label(), tryEnd = new Label(), handler = new Label();
|
||||||
|
int startSlot;
|
||||||
|
|
||||||
|
@Override protected void onMethodEnter() {
|
||||||
|
startSlot = newLocal(Type.LONG_TYPE);
|
||||||
|
invokeStatic(Type.getType(System.class), new org.objectweb.asm.commons.Method("nanoTime", "()J"));
|
||||||
|
storeLocal(startSlot);
|
||||||
|
visitLabel(tryStart);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override protected void onMethodExit(int opcode) {
|
||||||
|
if (opcode != ATHROW) emitRecord(); // athrow is covered by the catch-all handler below
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void visitMaxs(int maxStack, int maxLocals) {
|
||||||
|
visitLabel(tryEnd);
|
||||||
|
visitLabel(handler);
|
||||||
|
int ex = newLocal(Type.getType(Throwable.class));
|
||||||
|
storeLocal(ex);
|
||||||
|
emitRecord();
|
||||||
|
loadLocal(ex);
|
||||||
|
visitInsn(ATHROW);
|
||||||
|
visitTryCatchBlock(tryStart, tryEnd, handler, null);
|
||||||
|
super.visitMaxs(maxStack, maxLocals);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void emitRecord() {
|
||||||
|
visitLdcInsn(simple + "." + name);
|
||||||
|
invokeStatic(Type.getType(System.class), new org.objectweb.asm.commons.Method("nanoTime", "()J"));
|
||||||
|
loadLocal(startSlot);
|
||||||
|
visitInsn(LSUB);
|
||||||
|
invokeStatic(Type.getObjectType("demo/Timings"), new org.objectweb.asm.commons.Method("record", "(Ljava/lang/String;J)V"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, readerFlags);
|
||||||
|
return cw.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Throwable {
|
||||||
|
byte[] original = Bytes.of(Target.class);
|
||||||
|
byte[] viaAsm = instrument(original);
|
||||||
|
System.out.println("original " + original.length + " bytes, ASM-instrumented " + viaAsm.length + " bytes");
|
||||||
|
Check.that(java.lang.classfile.ClassFile.of().verify(viaAsm).isEmpty(), "ASM output passes ClassFile.verify()");
|
||||||
|
|
||||||
|
TransformDemo.report("ASM AdviceAdapter version", viaAsm);
|
||||||
|
Check.that(Timings.get("Target.boom").count() == 1 && Timings.get("Target.explode").count() == 1, "ASM version also records both throwing methods once");
|
||||||
|
Check.that(Timings.get("Target.fib").count() == 177, "ASM version: fib recorded 177 times");
|
||||||
|
Check.that(Timings.get("Target.pause").totalNanos() >= 50_000_000L, "ASM version: pause(50) recorded as at least 50 ms");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
/** The ParseDemo task done with ASM 9.11.1 (visitor API): list methods, count invoke targets. */
|
||||||
|
public class AsmParse {
|
||||||
|
record Result(List<String> methodLines, TreeMap<String, Integer> invokes, int major) { }
|
||||||
|
|
||||||
|
static Result parse(byte[] bytes) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
TreeMap<String, Integer> invokes = new TreeMap<>();
|
||||||
|
ClassReader cr = new ClassReader(bytes);
|
||||||
|
cr.accept(new ClassVisitor(Opcodes.ASM9) {
|
||||||
|
@Override public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] ex) {
|
||||||
|
lines.add(flags(access) + name + desc);
|
||||||
|
return new MethodVisitor(Opcodes.ASM9) {
|
||||||
|
@Override public void visitMethodInsn(int op, String owner, String n, String d, boolean itf) {
|
||||||
|
invokes.merge(owner + "." + n, 1, Integer::sum);
|
||||||
|
}
|
||||||
|
@Override public void visitInvokeDynamicInsn(String n, String d, org.objectweb.asm.Handle bsm, Object... args) {
|
||||||
|
invokes.merge("indy:" + n, 1, Integer::sum);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, ClassReader.SKIP_DEBUG);
|
||||||
|
return new Result(lines, invokes, cr.readShort(6));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same format as ParseDemo.flags: lower-case names, sorted, comma-joined. */
|
||||||
|
static String flags(int access) {
|
||||||
|
List<String> f = new ArrayList<>();
|
||||||
|
if ((access & Opcodes.ACC_PUBLIC) != 0) f.add("public");
|
||||||
|
if ((access & Opcodes.ACC_STATIC) != 0) f.add("static");
|
||||||
|
return String.join(",", f) + " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
byte[] bytes = Bytes.of(Target.class);
|
||||||
|
Result r = parse(bytes);
|
||||||
|
System.out.println("ASM sees major version " + r.major());
|
||||||
|
r.methodLines().forEach(l -> System.out.println(" " + l));
|
||||||
|
r.invokes().forEach((k, v) -> System.out.println(" " + v + " x " + k));
|
||||||
|
|
||||||
|
var cf = java.lang.classfile.ClassFile.of().parse(bytes);
|
||||||
|
Check.that(r.methodLines().equals(ParseDemo.methodLines(cf)), "ASM and java.lang.classfile list identical method lines");
|
||||||
|
Check.that(r.invokes().equals(ParseDemo.invokeCounts(cf)), "ASM and java.lang.classfile count identical invoke targets");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.classfile.ClassModel;
|
||||||
|
import java.lang.classfile.ClassTransform;
|
||||||
|
import java.lang.classfile.CodeElement;
|
||||||
|
import java.lang.classfile.Instruction;
|
||||||
|
import java.lang.classfile.MethodModel;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.ToLongFunction;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deliberately simple, INDICATIVE comparison (no JMH): parse and visit every instruction of the first N java.base classes,
|
||||||
|
* and parse + copy + write them back. Warm-up rounds first, then the median of the measured rounds.
|
||||||
|
* Time is the benchmark thread's own CPU time (not wall-clock), because the sandbox is a shared 2-vCPU machine and wall-clock
|
||||||
|
* numbers swing with whatever else is running. JIT and GC threads are therefore NOT included. Read the ratio, not the milliseconds.
|
||||||
|
*/
|
||||||
|
public class Bench {
|
||||||
|
static final int N = 2000, WARMUP = 4, ROUNDS = 9;
|
||||||
|
static final java.lang.management.ThreadMXBean CPU = java.lang.management.ManagementFactory.getThreadMXBean();
|
||||||
|
|
||||||
|
static long cfWalk(byte[] b) {
|
||||||
|
ClassModel cm = ClassFile.of().parse(b);
|
||||||
|
long n = 0;
|
||||||
|
for (MethodModel m : cm.methods()) {
|
||||||
|
if (m.code().isPresent()) {
|
||||||
|
for (CodeElement e : m.code().get()) if (e instanceof Instruction) n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
static long asmWalk(byte[] b) {
|
||||||
|
long[] n = {0};
|
||||||
|
new ClassReader(b).accept(new ClassVisitor(Opcodes.ASM9) {
|
||||||
|
@Override public MethodVisitor visitMethod(int a, String nm, String d, String s, String[] e) {
|
||||||
|
return new MethodVisitor(Opcodes.ASM9) {
|
||||||
|
@Override public void visitInsn(int o) { n[0]++; }
|
||||||
|
@Override public void visitIntInsn(int o, int x) { n[0]++; }
|
||||||
|
@Override public void visitVarInsn(int o, int x) { n[0]++; }
|
||||||
|
@Override public void visitTypeInsn(int o, String t) { n[0]++; }
|
||||||
|
@Override public void visitFieldInsn(int o, String a, String b, String c) { n[0]++; }
|
||||||
|
@Override public void visitMethodInsn(int o, String a, String b, String c, boolean i) { n[0]++; }
|
||||||
|
@Override public void visitInvokeDynamicInsn(String a, String b, org.objectweb.asm.Handle h, Object... r) { n[0]++; }
|
||||||
|
@Override public void visitJumpInsn(int o, org.objectweb.asm.Label l) { n[0]++; }
|
||||||
|
@Override public void visitLdcInsn(Object v) { n[0]++; }
|
||||||
|
@Override public void visitIincInsn(int v, int i) { n[0]++; }
|
||||||
|
@Override public void visitTableSwitchInsn(int a, int b, org.objectweb.asm.Label d, org.objectweb.asm.Label... l) { n[0]++; }
|
||||||
|
@Override public void visitLookupSwitchInsn(org.objectweb.asm.Label d, int[] k, org.objectweb.asm.Label[] l) { n[0]++; }
|
||||||
|
@Override public void visitMultiANewArrayInsn(String d, int x) { n[0]++; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
return n[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
static long cfCopy(byte[] b) {
|
||||||
|
ClassFile cf = ClassFile.of();
|
||||||
|
return cf.transformClass(cf.parse(b), ClassTransform.ACCEPT_ALL).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
static long asmCopy(byte[] b) {
|
||||||
|
ClassReader cr = new ClassReader(b);
|
||||||
|
ClassWriter cw = new ClassWriter(cr, 0);
|
||||||
|
cr.accept(cw, 0);
|
||||||
|
return cw.toByteArray().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
static double medianMs(List<byte[]> classes, ToLongFunction<byte[]> f) {
|
||||||
|
double[] t = new double[ROUNDS];
|
||||||
|
long sink = 0;
|
||||||
|
for (int i = 0; i < WARMUP; i++) for (byte[] b : classes) sink += f.applyAsLong(b);
|
||||||
|
for (int r = 0; r < ROUNDS; r++) {
|
||||||
|
long t0 = CPU.getCurrentThreadCpuTime();
|
||||||
|
for (byte[] b : classes) sink += f.applyAsLong(b);
|
||||||
|
t[r] = (CPU.getCurrentThreadCpuTime() - t0) / 1e6;
|
||||||
|
}
|
||||||
|
if (sink == 42) System.out.print("");
|
||||||
|
Arrays.sort(t);
|
||||||
|
return t[ROUNDS / 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
List<byte[]> classes = new ArrayList<>();
|
||||||
|
try (Stream<Path> s = Files.walk(Bytes.jrtRoot("java.base"))) {
|
||||||
|
for (Path p : (Iterable<Path>) s.filter(x -> x.toString().endsWith(".class") && !x.toString().endsWith("module-info.class")).sorted().limit(N)::iterator) {
|
||||||
|
classes.add(Files.readAllBytes(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
long total = classes.stream().mapToLong(b -> b.length).sum();
|
||||||
|
long insnCf = 0, insnAsm = 0;
|
||||||
|
for (byte[] b : classes) { insnCf += cfWalk(b); insnAsm += asmWalk(b); }
|
||||||
|
System.out.println("running on Java " + Runtime.version() + ", ASM 9.11.1; INDICATIVE numbers, thread CPU time, shared 2-vCPU sandbox, no JMH");
|
||||||
|
System.out.println(classes.size() + " classes from java.base, " + total / 1024 + " KiB; " + WARMUP + " warm-up rounds, median of " + ROUNDS);
|
||||||
|
System.out.println("instructions seen: java.lang.classfile " + insnCf + ", ASM " + insnAsm);
|
||||||
|
Check.that(insnCf > 0 && insnCf == insnAsm, "both walkers see exactly the same number of instructions");
|
||||||
|
|
||||||
|
double cfW = medianMs(classes, Bench::cfWalk), asmW = medianMs(classes, Bench::asmWalk);
|
||||||
|
double cfC = medianMs(classes, Bench::cfCopy), asmC = medianMs(classes, Bench::asmCopy);
|
||||||
|
System.out.printf("parse + visit every instruction : java.lang.classfile %7.1f ms ASM %7.1f ms (ASM / classfile = %.2f)%n", cfW, asmW, asmW / cfW);
|
||||||
|
System.out.printf("parse + copy + write back : java.lang.classfile %7.1f ms ASM %7.1f ms (ASM / classfile = %.2f)%n", cfC, asmC, asmC / cfC);
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.classfile.Label;
|
||||||
|
import java.lang.classfile.TypeKind;
|
||||||
|
import java.lang.constant.ClassDesc;
|
||||||
|
import java.lang.constant.MethodTypeDesc;
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static java.lang.constant.ConstantDescs.*;
|
||||||
|
|
||||||
|
/** Three ways to produce a bad class, and what each one looks like. */
|
||||||
|
public class BrokenGenerate {
|
||||||
|
static final ClassDesc C = ClassDesc.of("demo", "Broken");
|
||||||
|
|
||||||
|
/** static int pick(int n) { return n > 0 ? 1 : 2; } -- needs a StackMapTable because it branches. */
|
||||||
|
static byte[] branching(ClassFile cf) {
|
||||||
|
return cf.build(C, clb -> clb.withMethodBody("pick", MethodTypeDesc.of(CD_int, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||||
|
Label other = cob.newLabel(), done = cob.newLabel();
|
||||||
|
cob.iload(0).ifle(other).iconst_1().goto_(done).labelBinding(other).iconst_2().labelBinding(done).ireturn();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Throwable {
|
||||||
|
// 1. Same method, stack maps dropped on request.
|
||||||
|
byte[] noMaps = branching(ClassFile.of(ClassFile.StackMapsOption.DROP_STACK_MAPS));
|
||||||
|
List<VerifyError> v = ClassFile.of().verify(noMaps);
|
||||||
|
System.out.println("DROP_STACK_MAPS: verify() -> " + v.size() + " problem(s)");
|
||||||
|
v.forEach(e -> System.out.println(" " + e.getMessage().lines().findFirst().orElse("")));
|
||||||
|
try {
|
||||||
|
MethodHandles.lookup().defineClass(noMaps);
|
||||||
|
} catch (VerifyError e) {
|
||||||
|
System.out.println("DROP_STACK_MAPS: defineClass -> java.lang.VerifyError");
|
||||||
|
e.getMessage().lines().limit(3).forEach(l -> System.out.println(" " + l));
|
||||||
|
}
|
||||||
|
Check.that(!v.isEmpty(), "a branching method built without stack maps fails verification");
|
||||||
|
|
||||||
|
// 2. The default (stack maps generated when required) is fine for the very same code.
|
||||||
|
Check.that(ClassFile.of().verify(branching(ClassFile.of())).isEmpty(), "the same code with default options verifies");
|
||||||
|
|
||||||
|
// 3. Type confusion: ireturn on a method declared to return String. The builder does not stop you.
|
||||||
|
byte[] wrong = ClassFile.of().build(ClassDesc.of("demo", "Wrong"), clb -> clb.withMethodBody("bad",
|
||||||
|
MethodTypeDesc.of(CD_String), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob.iconst_1().ireturn()));
|
||||||
|
System.out.println("ireturn in a String method: build() succeeded (" + wrong.length + " bytes)");
|
||||||
|
List<VerifyError> w = ClassFile.of().verify(wrong);
|
||||||
|
w.forEach(e -> System.out.println(" verify: " + e.getMessage().lines().findFirst().orElse("")));
|
||||||
|
Check.that(!w.isEmpty(), "verify() catches a wrongly typed return");
|
||||||
|
|
||||||
|
// 4. Stack underflow while generating with stack maps: the generator itself throws.
|
||||||
|
try {
|
||||||
|
ClassFile.of().build(ClassDesc.of("demo", "Under"), clb -> clb.withMethodBody("u", MethodTypeDesc.of(CD_int),
|
||||||
|
ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||||
|
Label l = cob.newLabel();
|
||||||
|
cob.iadd().goto_(l).labelBinding(l).iconst_0().ireturn();
|
||||||
|
}));
|
||||||
|
System.out.println("underflow: build() succeeded");
|
||||||
|
Check.that(false, "stack underflow is caught while building");
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
Check.that(e instanceof IllegalArgumentException, "stack underflow is caught while building");
|
||||||
|
System.out.println("underflow: build() threw " + e.getClass().getName());
|
||||||
|
System.out.println(" " + e.getMessage().lines().findFirst().orElse(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. exceptionCatchAll(start, end, handler): three Labels, so swapping them compiles. verify() says nothing; the JVM objects.
|
||||||
|
byte[] swapped = ClassFile.of().build(ClassDesc.of("demo", "Swapped"), clb -> clb.withMethodBody("s",
|
||||||
|
MethodTypeDesc.of(CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||||
|
Label start = cob.newLabel(), end = cob.newLabel(), handler = cob.newLabel();
|
||||||
|
cob.labelBinding(start).iconst_1().labelBinding(end).ireturn()
|
||||||
|
.labelBinding(handler).pop().iconst_0().ireturn()
|
||||||
|
.exceptionCatchAll(handler, start, end); // WRONG order on purpose; correct is (start, end, handler)
|
||||||
|
}));
|
||||||
|
System.out.println("swapped labels: build() succeeded (" + swapped.length + " bytes), verify() -> " + ClassFile.of().verify(swapped).size() + " problem(s)");
|
||||||
|
try {
|
||||||
|
MethodHandles.lookup().defineClass(swapped);
|
||||||
|
Check.that(false, "the JVM rejects the swapped exception-table labels");
|
||||||
|
} catch (ClassFormatError e) {
|
||||||
|
System.out.println("swapped labels: defineClass -> " + e.getClass().getName() + ": " + e.getMessage());
|
||||||
|
Check.that(true, "the JVM rejects the swapped exception-table labels");
|
||||||
|
}
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.FileSystem;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Where class-file bytes come from in the demos. */
|
||||||
|
public final class Bytes {
|
||||||
|
private Bytes() { }
|
||||||
|
|
||||||
|
/** The bytes javac produced for one of our own classes, read from the class path. */
|
||||||
|
public static byte[] of(Class<?> c) {
|
||||||
|
try (InputStream in = c.getResourceAsStream(c.getSimpleName() + ".class")) {
|
||||||
|
return in.readAllBytes();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JDK class, read from the runtime image through the jrt: file system. */
|
||||||
|
public static byte[] jdk(String module, String internalName) {
|
||||||
|
try {
|
||||||
|
FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
|
||||||
|
return Files.readAllBytes(jrt.getPath("modules", module, internalName + ".class"));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Path jrtRoot(String module) {
|
||||||
|
return FileSystems.getFileSystem(URI.create("jrt:/")).getPath("modules", module);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
/** Tiny assertion helper: prints PASS/FAIL and fails the process at the end, like the other standalone modules. */
|
||||||
|
public final class Check {
|
||||||
|
private static int failures;
|
||||||
|
|
||||||
|
private Check() { }
|
||||||
|
|
||||||
|
public static void that(boolean ok, String what) {
|
||||||
|
System.out.println((ok ? "PASS " : "FAIL ") + what);
|
||||||
|
if (!ok) failures++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void finish() {
|
||||||
|
if (failures > 0) {
|
||||||
|
System.out.println(failures + " check(s) FAILED");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.classfile.Label;
|
||||||
|
import java.lang.classfile.TypeKind;
|
||||||
|
import java.lang.constant.ClassDesc;
|
||||||
|
import java.lang.constant.MethodTypeDesc;
|
||||||
|
import java.lang.invoke.MethodHandle;
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.lang.invoke.MethodType;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static java.lang.constant.ConstantDescs.*;
|
||||||
|
|
||||||
|
/** Generating a class from scratch with ClassFile.build, then defining it at runtime. */
|
||||||
|
public class GenerateDemo {
|
||||||
|
static final ClassDesc GENERATED = ClassDesc.of("demo", "Generated");
|
||||||
|
|
||||||
|
/** public class demo.Generated { add(int,int), hello(), sumTo(int), classify(int) }. */
|
||||||
|
static byte[] generate(ClassFile cf) {
|
||||||
|
return cf.build(GENERATED, clb -> clb
|
||||||
|
.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_SUPER)
|
||||||
|
.withMethodBody(INIT_NAME, MTD_void, ClassFile.ACC_PUBLIC, cob -> cob
|
||||||
|
.aload(0)
|
||||||
|
.invokespecial(CD_Object, INIT_NAME, MTD_void)
|
||||||
|
.return_())
|
||||||
|
// static int add(int a, int b) { return a + b; }
|
||||||
|
.withMethodBody("add", MethodTypeDesc.of(CD_int, CD_int, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||||
|
.iload(0).iload(1).iadd().ireturn())
|
||||||
|
// static String hello() { return "Hello from generated bytecode"; }
|
||||||
|
.withMethodBody("hello", MethodTypeDesc.of(CD_String), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||||
|
.ldc("Hello from generated bytecode").areturn())
|
||||||
|
// static long sumTo(int n) { long s = 0; for (int i = 1; i <= n; i++) s += i; return s; }
|
||||||
|
.withMethodBody("sumTo", MethodTypeDesc.of(CD_long, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> {
|
||||||
|
int s = cob.allocateLocal(TypeKind.LONG);
|
||||||
|
int i = cob.allocateLocal(TypeKind.INT);
|
||||||
|
Label loop = cob.newLabel(), end = cob.newLabel();
|
||||||
|
cob.lconst_0().lstore(s)
|
||||||
|
.iconst_1().istore(i)
|
||||||
|
.labelBinding(loop)
|
||||||
|
.iload(i).iload(0).if_icmpgt(end)
|
||||||
|
.lload(s).iload(i).i2l().ladd().lstore(s)
|
||||||
|
.iinc(i, 1)
|
||||||
|
.goto_(loop)
|
||||||
|
.labelBinding(end)
|
||||||
|
.lload(s).lreturn();
|
||||||
|
})
|
||||||
|
// static String classify(int n) { return n < 0 ? "negative" : "non-negative"; }
|
||||||
|
.withMethodBody("classify", MethodTypeDesc.of(CD_String, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, cob -> cob
|
||||||
|
.iload(0)
|
||||||
|
.ifThenElse(java.lang.classfile.Opcode.IFLT,
|
||||||
|
t -> t.ldc("negative"),
|
||||||
|
e -> e.ldc("non-negative"))
|
||||||
|
.areturn()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void exercise(Class<?> c, String how) throws Throwable {
|
||||||
|
MethodHandles.Lookup l = MethodHandles.publicLookup();
|
||||||
|
MethodHandle add = l.findStatic(c, "add", MethodType.methodType(int.class, int.class, int.class));
|
||||||
|
MethodHandle hello = l.findStatic(c, "hello", MethodType.methodType(String.class));
|
||||||
|
MethodHandle sum = l.findStatic(c, "sumTo", MethodType.methodType(long.class, int.class));
|
||||||
|
MethodHandle cls = l.findStatic(c, "classify", MethodType.methodType(String.class, int.class));
|
||||||
|
int a = (int) add.invoke(2, 3);
|
||||||
|
String h = (String) hello.invoke();
|
||||||
|
long s = (long) sum.invoke(100);
|
||||||
|
String neg = (String) cls.invoke(-4), pos = (String) cls.invoke(4);
|
||||||
|
System.out.println("[" + how + "] add(2,3)=" + a + " hello()=" + h + " sumTo(100)=" + s
|
||||||
|
+ " classify(-4)=" + neg + " classify(4)=" + pos);
|
||||||
|
Check.that(a == 5 && s == 5050L && "negative".equals(neg) && "non-negative".equals(pos), how + ": generated methods return the right values");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Throwable {
|
||||||
|
ClassFile cf = ClassFile.of();
|
||||||
|
byte[] bytes = generate(cf);
|
||||||
|
Path outDir = Path.of(args.length > 0 ? args[0] : "target/gen/demo");
|
||||||
|
Files.createDirectories(outDir);
|
||||||
|
Files.write(outDir.resolve("Generated.class"), bytes);
|
||||||
|
System.out.println("generated " + bytes.length + " bytes, major version " + cf.parse(bytes).majorVersion()
|
||||||
|
+ " (wrote " + outDir.resolve("Generated.class") + ")");
|
||||||
|
|
||||||
|
// 1. Verify without loading: returns a list of VerifyError, empty if the class is well formed.
|
||||||
|
List<VerifyError> problems = cf.verify(bytes);
|
||||||
|
System.out.println("ClassFile.verify(bytes) -> " + problems.size() + " problem(s)");
|
||||||
|
Check.that(problems.isEmpty(), "verify() finds nothing wrong with the generated class");
|
||||||
|
|
||||||
|
// 2. Define it as an ordinary class in this package (Lookup.defineClass needs the same package as the lookup class).
|
||||||
|
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||||
|
Class<?> normal = lookup.defineClass(bytes);
|
||||||
|
System.out.println("defineClass -> " + normal.getName() + " hidden=" + normal.isHidden()
|
||||||
|
+ " findable by name=" + (Class.forName("demo.Generated") == normal));
|
||||||
|
exercise(normal, "defineClass");
|
||||||
|
|
||||||
|
// 3. Define the same bytes as a hidden class: no name anyone can resolve, unloadable with its defining loader's GC.
|
||||||
|
MethodHandles.Lookup hiddenLookup = lookup.defineHiddenClass(bytes, true);
|
||||||
|
Class<?> hidden = hiddenLookup.lookupClass();
|
||||||
|
System.out.println("defineHiddenClass -> name starts with 'demo.Generated/': " + hidden.getName().startsWith("demo.Generated/")
|
||||||
|
+ " hidden=" + hidden.isHidden() + " distinct from the normal class=" + (hidden != normal));
|
||||||
|
exercise(hidden, "hidden");
|
||||||
|
try {
|
||||||
|
Class.forName(hidden.getName());
|
||||||
|
} catch (ClassNotFoundException e) {
|
||||||
|
System.out.println("Class.forName(hidden name) -> ClassNotFoundException (hidden classes cannot be found by name)");
|
||||||
|
}
|
||||||
|
Check.that(hidden.isHidden() && !normal.isHidden(), "hidden class is hidden, the other is not");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassElement;
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.classfile.ClassModel;
|
||||||
|
import java.lang.classfile.CodeElement;
|
||||||
|
import java.lang.classfile.FieldModel;
|
||||||
|
import java.lang.classfile.Instruction;
|
||||||
|
import java.lang.classfile.MethodModel;
|
||||||
|
import java.lang.classfile.attribute.SourceFileAttribute;
|
||||||
|
import java.lang.classfile.instruction.InvokeDynamicInstruction;
|
||||||
|
import java.lang.classfile.instruction.InvokeInstruction;
|
||||||
|
import java.lang.reflect.AccessFlag;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/** Reading a class with java.lang.classfile: ClassFile.of().parse(...) and walking the model. */
|
||||||
|
public class ParseDemo {
|
||||||
|
|
||||||
|
/** One line per method: flags name descriptor. Shared with the ASM comparison, which must print the same lines. */
|
||||||
|
static List<String> methodLines(ClassModel cm) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
for (MethodModel m : cm.methods()) {
|
||||||
|
lines.add(flags(m.flags().flags()) + m.methodName().stringValue() + m.methodType().stringValue());
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String flags(java.util.Set<AccessFlag> fs) {
|
||||||
|
return fs.stream().map(f -> f.name().toLowerCase()).sorted().collect(Collectors.joining(",")) + " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Calls per "owner.name" in all method bodies, using a pattern-matching switch over code elements. */
|
||||||
|
static TreeMap<String, Integer> invokeCounts(ClassModel cm) {
|
||||||
|
TreeMap<String, Integer> counts = new TreeMap<>();
|
||||||
|
for (MethodModel m : cm.methods()) {
|
||||||
|
m.code().ifPresent(code -> {
|
||||||
|
for (CodeElement e : code) {
|
||||||
|
switch (e) {
|
||||||
|
case InvokeInstruction i -> counts.merge(
|
||||||
|
i.owner().asInternalName() + "." + i.name().stringValue(), 1, Integer::sum);
|
||||||
|
case InvokeDynamicInstruction i -> counts.merge(
|
||||||
|
"indy:" + i.name().stringValue(), 1, Integer::sum);
|
||||||
|
default -> { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
byte[] bytes = Bytes.of(Target.class);
|
||||||
|
ClassModel cm = ClassFile.of().parse(bytes);
|
||||||
|
|
||||||
|
System.out.println("== header ==");
|
||||||
|
System.out.println("bytes : " + bytes.length);
|
||||||
|
System.out.println("this : " + cm.thisClass().asInternalName());
|
||||||
|
System.out.println("super : " + cm.superclass().orElseThrow().asInternalName());
|
||||||
|
System.out.println("version : " + cm.majorVersion() + "." + cm.minorVersion()
|
||||||
|
+ " (ClassFile.JAVA_25_VERSION = " + ClassFile.JAVA_25_VERSION + ")");
|
||||||
|
System.out.println("flags : " + flags(cm.flags().flags()));
|
||||||
|
System.out.println("constant pool : " + cm.constantPool().size() + " slots");
|
||||||
|
|
||||||
|
System.out.println("\n== fields ==");
|
||||||
|
for (FieldModel f : cm.fields()) {
|
||||||
|
System.out.println(flags(f.flags().flags()) + f.fieldName().stringValue() + " " + f.fieldType().stringValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("\n== methods ==");
|
||||||
|
methodLines(cm).forEach(System.out::println);
|
||||||
|
|
||||||
|
System.out.println("\n== class elements, in file order (the model is a stream of elements) ==");
|
||||||
|
for (ClassElement ce : cm) {
|
||||||
|
String d = switch (ce) {
|
||||||
|
case MethodModel m -> "method " + m.methodName().stringValue();
|
||||||
|
case FieldModel f -> "field " + f.fieldName().stringValue();
|
||||||
|
case SourceFileAttribute a -> "SourceFile=" + a.sourceFile().stringValue();
|
||||||
|
default -> ce.getClass().getSimpleName().replaceAll("Impl$", "");
|
||||||
|
};
|
||||||
|
System.out.println(" " + d);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("\n== fib(I)I, instruction by instruction ==");
|
||||||
|
MethodModel fib = cm.methods().stream().filter(m -> m.methodName().equalsString("fib")).findFirst().orElseThrow();
|
||||||
|
for (CodeElement e : fib.code().orElseThrow()) {
|
||||||
|
if (e instanceof Instruction i) {
|
||||||
|
String extra = e instanceof InvokeInstruction inv
|
||||||
|
? " " + inv.owner().asInternalName() + "." + inv.name().stringValue() + inv.type().stringValue() : "";
|
||||||
|
System.out.println(" " + i.opcode() + extra);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("\n== invoke targets in the whole class ==");
|
||||||
|
TreeMap<String, Integer> counts = invokeCounts(cm);
|
||||||
|
counts.forEach((k, v) -> System.out.println(" " + v + " x " + k));
|
||||||
|
|
||||||
|
System.out.println("\n== a JDK class from the runtime image: java.lang.String ==");
|
||||||
|
byte[] sb = Bytes.jdk("java.base", "java/lang/String");
|
||||||
|
ClassModel string = ClassFile.of().parse(sb);
|
||||||
|
System.out.println("bytes " + sb.length + ", major " + string.majorVersion() + ", methods " + string.methods().size()
|
||||||
|
+ ", fields " + string.fields().size() + ", interfaces " + string.interfaces().size());
|
||||||
|
|
||||||
|
Check.that(cm.majorVersion() == ClassFile.JAVA_25_VERSION, "Target.class is class-file version 69 (compiled with --release 25)");
|
||||||
|
Check.that(cm.methods().size() == 8, "Target has 8 methods (constructor + 7)");
|
||||||
|
Check.that(counts.getOrDefault("demo/Target.fib", 0) == 2, "fib calls itself twice");
|
||||||
|
Check.that(counts.containsKey("indy:makeConcatWithConstants"), "greet() uses invokedynamic string concatenation");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
/** The class we inspect and instrument. Deliberately small, and it covers the interesting shapes:
|
||||||
|
* a recursive method, a loop, string concatenation (invokedynamic), a method that sleeps and one that throws. */
|
||||||
|
public class Target {
|
||||||
|
private final String name;
|
||||||
|
private int calls;
|
||||||
|
|
||||||
|
public Target(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int fib(int n) {
|
||||||
|
return n < 2 ? n : fib(n - 1) + fib(n - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long sumTo(int n) {
|
||||||
|
long s = 0;
|
||||||
|
for (int i = 1; i <= n; i++) {
|
||||||
|
s += i;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String greet(String who) {
|
||||||
|
calls++;
|
||||||
|
return "Hello, " + who + " from " + name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void pause(long millis) throws InterruptedException {
|
||||||
|
Thread.sleep(millis);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void boom() {
|
||||||
|
throw new IllegalStateException("boom");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int explode(int[] a) {
|
||||||
|
return a[5]; // throws from the JVM (AIOOBE), not from an explicit athrow
|
||||||
|
}
|
||||||
|
|
||||||
|
public int calls() {
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassBuilder;
|
||||||
|
import java.lang.classfile.ClassElement;
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.classfile.ClassModel;
|
||||||
|
import java.lang.classfile.ClassTransform;
|
||||||
|
import java.lang.classfile.CodeBuilder;
|
||||||
|
import java.lang.classfile.CodeElement;
|
||||||
|
import java.lang.classfile.CodeTransform;
|
||||||
|
import java.lang.classfile.Label;
|
||||||
|
import java.lang.classfile.MethodModel;
|
||||||
|
import java.lang.classfile.MethodTransform;
|
||||||
|
import java.lang.classfile.TypeKind;
|
||||||
|
import java.lang.classfile.instruction.ReturnInstruction;
|
||||||
|
import java.lang.constant.ClassDesc;
|
||||||
|
import java.lang.constant.MethodTypeDesc;
|
||||||
|
|
||||||
|
import static java.lang.constant.ConstantDescs.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts timing around every method body of a class using java.lang.classfile transforms.
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* ClassTransform -- looks at each class element; for a method it hands the MethodModel to a MethodTransform
|
||||||
|
* MethodTransform -- transformingCode(...) forwards the Code attribute to a CodeTransform
|
||||||
|
* CodeTransform -- sees every instruction; atStart/atEnd bracket the whole body
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
public final class TimingTransform {
|
||||||
|
static final ClassDesc SYSTEM = ClassDesc.of("java.lang.System");
|
||||||
|
static final ClassDesc TIMINGS = ClassDesc.of("demo.Timings");
|
||||||
|
static final MethodTypeDesc NANO_TIME = MethodTypeDesc.of(CD_long);
|
||||||
|
static final MethodTypeDesc RECORD = MethodTypeDesc.of(CD_void, CD_String, CD_long);
|
||||||
|
|
||||||
|
private TimingTransform() { }
|
||||||
|
|
||||||
|
/** @param alsoOnException false = time only normal returns (the naive version); true = also when an exception leaves the method */
|
||||||
|
public static byte[] instrument(byte[] original, boolean alsoOnException) {
|
||||||
|
ClassFile cf = ClassFile.of();
|
||||||
|
ClassModel model = cf.parse(original);
|
||||||
|
String owner = model.thisClass().asInternalName();
|
||||||
|
|
||||||
|
ClassTransform perClass = (ClassBuilder cb, ClassElement ce) -> {
|
||||||
|
if (ce instanceof MethodModel mm && mm.code().isPresent() && !mm.methodName().equalsString("<init>")) {
|
||||||
|
String label = owner.substring(owner.lastIndexOf('/') + 1) + "." + mm.methodName().stringValue();
|
||||||
|
cb.transformMethod(mm, MethodTransform.transformingCode(
|
||||||
|
CodeTransform.ofStateful(() -> new Timer(label, alsoOnException))));
|
||||||
|
} else {
|
||||||
|
cb.with(ce); // everything else is copied unchanged
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return cf.transformClass(model, perClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One instance per method body (ofStateful), so the local-variable slot and labels are per method. */
|
||||||
|
private static final class Timer implements CodeTransform {
|
||||||
|
private final String label;
|
||||||
|
private final boolean alsoOnException;
|
||||||
|
private int startSlot;
|
||||||
|
private Label tryStart, tryEnd;
|
||||||
|
|
||||||
|
Timer(String label, boolean alsoOnException) {
|
||||||
|
this.label = label;
|
||||||
|
this.alsoOnException = alsoOnException;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void atStart(CodeBuilder b) {
|
||||||
|
startSlot = b.allocateLocal(TypeKind.LONG); // a fresh local; max_locals is recomputed for us
|
||||||
|
b.invokestatic(SYSTEM, "nanoTime", NANO_TIME).lstore(startSlot);
|
||||||
|
if (alsoOnException) {
|
||||||
|
tryStart = b.newLabel();
|
||||||
|
tryEnd = b.newLabel();
|
||||||
|
b.labelBinding(tryStart);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(CodeBuilder b, CodeElement e) {
|
||||||
|
if (e instanceof ReturnInstruction) {
|
||||||
|
emitRecord(b); // the return value is on the stack; our code is stack-neutral
|
||||||
|
}
|
||||||
|
b.with(e); // forward the original element
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void atEnd(CodeBuilder b) {
|
||||||
|
if (!alsoOnException) return;
|
||||||
|
b.labelBinding(tryEnd);
|
||||||
|
Label handler = b.newLabel();
|
||||||
|
b.labelBinding(handler);
|
||||||
|
int ex = b.allocateLocal(TypeKind.REFERENCE);
|
||||||
|
b.astore(ex);
|
||||||
|
emitRecord(b);
|
||||||
|
b.aload(ex).athrow();
|
||||||
|
b.exceptionCatchAll(tryStart, tryEnd, handler); // (start, end, handler): catch-any over the original body
|
||||||
|
}
|
||||||
|
|
||||||
|
private void emitRecord(CodeBuilder b) {
|
||||||
|
b.ldc(label)
|
||||||
|
.invokestatic(SYSTEM, "nanoTime", NANO_TIME)
|
||||||
|
.lload(startSlot)
|
||||||
|
.lsub()
|
||||||
|
.invokestatic(TIMINGS, "record", RECORD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.LongAdder;
|
||||||
|
|
||||||
|
/** Sink for the timing code we inject. Public, because the injected bytecode calls it from another class loader. */
|
||||||
|
public final class Timings {
|
||||||
|
public record Stat(long count, long totalNanos) { }
|
||||||
|
|
||||||
|
private static final Map<String, LongAdder> COUNT = new ConcurrentHashMap<>();
|
||||||
|
private static final Map<String, LongAdder> NANOS = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private Timings() { }
|
||||||
|
|
||||||
|
/** Called from instrumented code. Signature (String, long) is mirrored in the ClassFile and ASM transformers. */
|
||||||
|
public static void record(String method, long nanos) {
|
||||||
|
COUNT.computeIfAbsent(method, k -> new LongAdder()).increment();
|
||||||
|
NANOS.computeIfAbsent(method, k -> new LongAdder()).add(nanos);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Stat get(String method) {
|
||||||
|
LongAdder c = COUNT.get(method);
|
||||||
|
return c == null ? new Stat(0, 0) : new Stat(c.sum(), NANOS.get(method).sum());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void reset() {
|
||||||
|
COUNT.clear();
|
||||||
|
NANOS.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Instrument demo.Target with TimingTransform, load the result in an isolated class loader, call it, read the timings. */
|
||||||
|
public class TransformDemo {
|
||||||
|
|
||||||
|
/** Defines `transformed` as demo.Target in its own loader; everything else (Timings, ...) comes from the parent. */
|
||||||
|
static final class Loader extends ClassLoader {
|
||||||
|
private final byte[] target;
|
||||||
|
Loader(byte[] target) { super(TransformDemo.class.getClassLoader()); this.target = target; }
|
||||||
|
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||||
|
if (name.equals("demo.Target")) {
|
||||||
|
synchronized (getClassLoadingLock(name)) {
|
||||||
|
Class<?> c = findLoadedClass(name);
|
||||||
|
if (c == null) c = defineClass(name, target, 0, target.length);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.loadClass(name, resolve);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void drive(Class<?> target) throws Throwable {
|
||||||
|
var fib = target.getMethod("fib", int.class);
|
||||||
|
var sum = target.getMethod("sumTo", int.class);
|
||||||
|
var boom = target.getMethod("boom");
|
||||||
|
var explode = target.getMethod("explode", int[].class);
|
||||||
|
var pause = target.getMethod("pause", long.class);
|
||||||
|
var greet = target.getMethod("greet", String.class);
|
||||||
|
Object t = target.getConstructor(String.class).newInstance("loader-2");
|
||||||
|
|
||||||
|
fib.invoke(null, 10);
|
||||||
|
sum.invoke(null, 1000);
|
||||||
|
greet.invoke(t, "Ankur");
|
||||||
|
pause.invoke(t, 50L);
|
||||||
|
try { boom.invoke(null); } catch (java.lang.reflect.InvocationTargetException e) { System.out.println(" boom() threw " + e.getCause()); }
|
||||||
|
try { explode.invoke(null, (Object) new int[3]); } catch (java.lang.reflect.InvocationTargetException e) { System.out.println(" explode() threw " + e.getCause().getClass().getSimpleName()); }
|
||||||
|
}
|
||||||
|
|
||||||
|
static void report(String title, byte[] bytes) throws Throwable {
|
||||||
|
Timings.reset();
|
||||||
|
System.out.println("-- " + title + " (" + bytes.length + " bytes; verify() problems: " + ClassFile.of().verify(bytes).size() + ")");
|
||||||
|
Class<?> c = new Loader(bytes).loadClass("demo.Target");
|
||||||
|
Check.that(c != Target.class, title + ": demo.Target here is a different Class object than the one on the class path");
|
||||||
|
drive(c);
|
||||||
|
for (String m : List.of("fib", "sumTo", "greet", "pause", "boom", "explode")) {
|
||||||
|
Timings.Stat s = Timings.get("Target." + m);
|
||||||
|
System.out.printf(" %-8s recorded %3d call(s)%n", m, s.count());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Throwable {
|
||||||
|
byte[] original = Bytes.of(Target.class);
|
||||||
|
Path dir = Path.of(args.length > 0 ? args[0] : "target/instrumented");
|
||||||
|
Files.createDirectories(dir.resolve("naive/demo"));
|
||||||
|
Files.createDirectories(dir.resolve("full/demo"));
|
||||||
|
|
||||||
|
byte[] naive = TimingTransform.instrument(original, false);
|
||||||
|
byte[] full = TimingTransform.instrument(original, true);
|
||||||
|
Files.write(dir.resolve("naive/demo/Target.class"), naive);
|
||||||
|
Files.write(dir.resolve("full/demo/Target.class"), full);
|
||||||
|
System.out.println("original " + original.length + " bytes, naive " + naive.length + " bytes, with exception handler " + full.length + " bytes");
|
||||||
|
|
||||||
|
report("naive: time normal returns only", naive);
|
||||||
|
Timings.Stat naiveBoom = Timings.get("Target.boom"), naiveExplode = Timings.get("Target.explode"), naiveFib = Timings.get("Target.fib");
|
||||||
|
Check.that(naiveBoom.count() == 0 && naiveExplode.count() == 0, "naive version never records the two methods that throw");
|
||||||
|
Check.that(naiveFib.count() == 177, "fib(10) makes 177 calls and 177 timings were recorded (recursion included)");
|
||||||
|
|
||||||
|
report("full: also time when an exception leaves the method", full);
|
||||||
|
Check.that(Timings.get("Target.boom").count() == 1 && Timings.get("Target.explode").count() == 1, "exception-safe version records boom() and explode() once each");
|
||||||
|
Check.that(Timings.get("Target.fib").count() == 177, "fib still recorded 177 times");
|
||||||
|
Check.that(Timings.get("Target.sumTo").count() == 1 && Timings.get("Target.greet").count() == 1, "sumTo and greet recorded once each");
|
||||||
|
Check.that(Timings.get("Target.pause").totalNanos() >= 50_000_000L, "pause(50) was recorded as at least 50 ms (>= 50,000,000 ns)");
|
||||||
|
|
||||||
|
// Behaviour is unchanged: the transformed class still computes the same answers.
|
||||||
|
Class<?> c = new Loader(full).loadClass("demo.Target");
|
||||||
|
Check.that((int) c.getMethod("fib", int.class).invoke(null, 20) == Target.fib(20), "fib(20) gives the same answer before and after");
|
||||||
|
Check.that(((Long) c.getMethod("sumTo", int.class).invoke(null, 12345)) == Target.sumTo(12345), "sumTo(12345) gives the same answer before and after");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package demo;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.lang.classfile.ClassFile;
|
||||||
|
|
||||||
|
/** What happens when the class file is newer than the reader. Patches the major-version bytes of Target.class. */
|
||||||
|
public class VersionLimits {
|
||||||
|
static byte[] withMajor(byte[] original, int major) {
|
||||||
|
byte[] b = original.clone();
|
||||||
|
b[6] = (byte) (major >> 8);
|
||||||
|
b[7] = (byte) major;
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String tryClassFile(byte[] b) {
|
||||||
|
try {
|
||||||
|
var cm = ClassFile.of().parse(b);
|
||||||
|
return "parsed, " + cm.methods().size() + " methods";
|
||||||
|
} catch (Throwable t) {
|
||||||
|
return t.getClass().getName() + ": " + t.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String tryAsm(byte[] b) {
|
||||||
|
try {
|
||||||
|
int[] n = {0};
|
||||||
|
new ClassReader(b).accept(new ClassVisitor(Opcodes.ASM9) {
|
||||||
|
@Override public org.objectweb.asm.MethodVisitor visitMethod(int a, String nm, String d, String s, String[] e) { n[0]++; return null; }
|
||||||
|
}, 0);
|
||||||
|
return "parsed, " + n[0] + " methods";
|
||||||
|
} catch (Throwable t) {
|
||||||
|
return t.getClass().getName() + ": " + t.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
byte[] t = Bytes.of(Target.class);
|
||||||
|
System.out.println("running on Java " + Runtime.version().feature() + "; ClassFile.latestMajorVersion() = " + ClassFile.latestMajorVersion()
|
||||||
|
+ "; ASM Opcodes.V25=" + Opcodes.V25 + ", V28=" + Opcodes.V28);
|
||||||
|
for (int major : new int[]{69, 70, 72, 73, 99}) {
|
||||||
|
byte[] b = withMajor(t, major);
|
||||||
|
System.out.println("major " + major + ":");
|
||||||
|
System.out.println(" java.lang.classfile : " + tryClassFile(b));
|
||||||
|
System.out.println(" ASM 9.11.1 : " + tryAsm(b));
|
||||||
|
}
|
||||||
|
Check.that(tryClassFile(withMajor(t, 69)).startsWith("parsed"), "major 69 parses with java.lang.classfile");
|
||||||
|
Check.that(tryClassFile(withMajor(t, ClassFile.latestMajorVersion() + 1)).startsWith("java.lang.IllegalArgumentException"), "one version above the JDK's own is rejected by java.lang.classfile");
|
||||||
|
Check.that(tryAsm(withMajor(t, Opcodes.V28)).startsWith("parsed"), "ASM 9.11.1 still reads major 72 (Java 28)");
|
||||||
|
Check.that(tryAsm(withMajor(t, Opcodes.V28 + 1)).startsWith("java.lang.IllegalArgumentException"), "ASM 9.11.1 rejects major 73");
|
||||||
|
Check.finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
target/
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# crac: one Spring Boot service started four ways
|
||||||
|
|
||||||
|
Companion module for the ankurm.com post **Spring Boot with CRaC: Checkpoint/Restore Startup Compared with the JDK AOT Cache and a Native Image**.
|
||||||
|
No `docs/` folder: this README, the sources and the raw files in [`output/`](output) are the documentation; the explanations live in the post.
|
||||||
|
|
||||||
|
## What was tested against
|
||||||
|
|
||||||
|
| Thing | Version |
|
||||||
|
|---|---|
|
||||||
|
| Spring Boot | 4.2.0 (Spring Framework 7.1.0, Tomcat 11.0.27), `webmvc` + `validation` + `actuator`, no database |
|
||||||
|
| `org.crac:crac` | 1.5.0 (managed by the Boot 4.2.0 BOM) |
|
||||||
|
| Plain JVM and AOT cache | Temurin 25.0.5.1+2 (LTS) |
|
||||||
|
| CRaC JVM | Azul Zulu 25.38.203 with CRaC, `25.0.5.1.1` (LTS) |
|
||||||
|
| Native image | Oracle GraalVM 25.0.4+7.1, `native-image` 25.0.4, Spring Boot's `native` profile |
|
||||||
|
| Machine | 2 vCPU, 8 GB, Linux 6.18 (Firecracker VM), running as root. The host was shared with other jobs, so treat milliseconds as indicative and ratios as the result |
|
||||||
|
|
||||||
|
## The service
|
||||||
|
|
||||||
|
`OrderController` (`/ping`, `POST /orders`, `GET /orders/{id}`), `InfoController` (`/info`: pid, restore count, an environment variable read at start-up and read now),
|
||||||
|
`RestoreTracker` (a plain `org.crac.Resource`), and three profiles of the audit-log resource:
|
||||||
|
|
||||||
|
| Profile | Class | Behaviour |
|
||||||
|
|---|---|---|
|
||||||
|
| (none) | - | no file is held open |
|
||||||
|
| `leaky` | [`LeakyAuditLog`](src/main/java/com/ankurm/crac/LeakyAuditLog.java) | opens a file in the constructor and keeps it: a checkpoint is refused |
|
||||||
|
| `managed` | [`ManagedAuditLog`](src/main/java/com/ankurm/crac/ManagedAuditLog.java) | opens in `start()`, closes in `stop()`: Spring closes it before the checkpoint and reopens it after the restore |
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export JDK_PLAIN=/path/to/temurin-25 JDK_CRAC=/path/to/zulu-25-crac JDK_GRAAL=/path/to/graalvm-25 # defaults are in scripts/env.sh
|
||||||
|
./scripts/build.sh # jar + extracted layout
|
||||||
|
./scripts/native.sh # native image (5 to 14 minutes, 5 GB peak)
|
||||||
|
./scripts/versions.sh # output/01
|
||||||
|
./scripts/checkpoints.sh # CRaC checkpoints (start-up and warmed-up) and AOT caches; output/02
|
||||||
|
./scripts/resources.sh # open file, managed file, environment variables, secrets in the image; output/03-05
|
||||||
|
./scripts/engines.sh # warp and CRIU engines; output/06
|
||||||
|
./scripts/bench.sh 10 # interleaved rounds of seven start-up configurations; output/08
|
||||||
|
./scripts/cold.sh 5 # the same with the page cache emptied (root); output/09
|
||||||
|
./scripts/run-all.sh # everything above, about 25 minutes
|
||||||
|
```
|
||||||
|
|
||||||
|
The scripts use a private port (18771) and a work directory (`/tmp/crac-work`) so they do not collide with other services. Checkpoints, caches and logs live there and are not committed.
|
||||||
|
|
||||||
|
## Captured output
|
||||||
|
|
||||||
|
| File | Produced by | What it shows |
|
||||||
|
|---|---|---|
|
||||||
|
| `01-versions.txt` | `versions.sh` | the exact JDKs, Spring jars and machine |
|
||||||
|
| `02-create.txt` | `checkpoints.sh` | creating the two checkpoints and two AOT caches: time, size, log lines |
|
||||||
|
| `03-leaky.txt` | `resources.sh` | `CheckpointOpenFileException`: start-up checkpoint kills the app (exit 1), `jcmd` checkpoint is refused and the app keeps running |
|
||||||
|
| `04-managed.txt` | `resources.sh` | the fixed file: close/open hooks, Spring's lifecycle restart, the audit file continuing across a restore |
|
||||||
|
| `05-environment.txt` | `resources.sh` | `System.getenv()` after restore vs a value cached in a field, a new pid, a secret found in `core.img` |
|
||||||
|
| `06-engines.txt` | `engines.sh` | `warp` and `criuengine` both checkpoint and restore here; what CRIU needs from the process |
|
||||||
|
| `07-native-build.txt` | `native.sh` (summary of the real build log) | native build time, memory, image size |
|
||||||
|
| `08-bench.txt` | `bench.sh` | median and range of ten rounds: ready time, first POST, steady state, RSS |
|
||||||
|
| `09-cold-cache.txt` | `cold.sh` | ready time with an empty page cache |
|
||||||
|
|
||||||
|
Timings and RSS differ from run to run; everything else (exceptions, log lines, counts) is stable.
|
||||||
|
|
||||||
|
## Things that are not covered
|
||||||
|
|
||||||
|
No Docker image was built or run for CRaC; no Kubernetes, no Liberica CRaC JDK, no database or connection pool, and no restore on a different machine or CPU.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
== machine
|
||||||
|
Linux 6.18.44-fc-v880
|
||||||
|
cpus: 2
|
||||||
|
memory MB: 8023
|
||||||
|
|
||||||
|
== plain JVM and AOT cache
|
||||||
|
openjdk version "25.0.5.1" 2026-11-17 LTS
|
||||||
|
OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
|
||||||
|
OpenJDK 64-Bit Server VM Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS, mixed mode, sharing)
|
||||||
|
|
||||||
|
== CRaC JVM
|
||||||
|
openjdk version "25.0.5.1.1" 2026-11-17 LTS
|
||||||
|
OpenJDK Runtime Environment Zulu25.38+203-CRaC-CA (build 25.0.5.1.1+1-LTS)
|
||||||
|
OpenJDK 64-Bit Server VM Zulu25.38+203-CRaC-CA (build 25.0.5.1.1+1-LTS, mixed mode, sharing)
|
||||||
|
engines shipped: criu criuhelper libcriuengine.so libwarp.so
|
||||||
|
|
||||||
|
== native-image
|
||||||
|
native-image 25.0.4 2026-07-21
|
||||||
|
GraalVM Runtime Environment Oracle GraalVM 25.0.4+7.1 (build 25.0.4+7-LTS-jvmci-b01)
|
||||||
|
Substrate VM Oracle GraalVM 25.0.4+7.1 (build 25.0.4+7-LTS, serial gc, compressed references)
|
||||||
|
|
||||||
|
== Spring
|
||||||
|
Implementation-Version: 4.2.0
|
||||||
|
crac-1.5.0.jar
|
||||||
|
spring-boot-4.2.0.jar
|
||||||
|
spring-boot-actuator-4.2.0.jar
|
||||||
|
spring-boot-actuator-autoconfigure-4.2.0.jar
|
||||||
|
spring-boot-autoconfigure-4.2.0.jar
|
||||||
|
spring-boot-health-4.2.0.jar
|
||||||
|
spring-boot-http-converter-4.2.0.jar
|
||||||
|
spring-boot-jackson-4.2.0.jar
|
||||||
|
spring-boot-jarmode-tools-4.2.0.jar
|
||||||
|
spring-boot-micrometer-metrics-4.2.0.jar
|
||||||
|
spring-boot-micrometer-observation-4.2.0.jar
|
||||||
|
spring-boot-servlet-4.2.0.jar
|
||||||
|
spring-boot-tomcat-4.2.0.jar
|
||||||
|
spring-boot-validation-4.2.0.jar
|
||||||
|
spring-boot-web-server-4.2.0.jar
|
||||||
|
spring-boot-webmvc-4.2.0.jar
|
||||||
|
spring-context-7.1.0.jar
|
||||||
|
spring-core-7.1.0.jar
|
||||||
|
spring-webmvc-7.1.0.jar
|
||||||
|
tomcat-embed-core-11.0.27.jar
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
== CRaC checkpoint at start-up (-Dspring.context.checkpoint=onRefresh)
|
||||||
|
process exited after 6989 ms; checkpoint dir: core.img engine size: 110 MB
|
||||||
|
INFO 9383 --- [crac-demo] [ main] com.ankurm.crac.CracDemoApplication : Starting CracDemoApplication v1.0.0 using Java 25.0.5.1.1 with PID 9383 (<work>/app/crac-demo-1.0.0.jar started by root in <work>)
|
||||||
|
RestoreTracker: beforeCheckpoint
|
||||||
|
[6.927s][info][crac] Checkpoint ...
|
||||||
|
3230.887277: warp: Checkpoint 9383 to <work>/cp-refresh
|
||||||
|
3230.929900: warp: Checkpoint successful!
|
||||||
|
|
||||||
|
== CRaC checkpoint after warm-up (300 POST + 300 GET, then jcmd JDK.checkpoint)
|
||||||
|
jcmd JDK.checkpoint returned after 506 ms; process gone after 616 ms; checkpoint size: 136 MB
|
||||||
|
INFO 9520 --- [crac-demo] [Attach Listener] jdk.crac : Starting checkpoint
|
||||||
|
RestoreTracker: beforeCheckpoint
|
||||||
|
[7.441s][info][crac] Checkpoint ...
|
||||||
|
3238.421212: warp: Checkpoint 9520 to <work>/cp-warm
|
||||||
|
3238.499849: warp: Checkpoint successful!
|
||||||
|
|
||||||
|
== JDK AOT cache (JEP 514), context-only training
|
||||||
|
training took 11045 ms; 60 MB
|
||||||
|
|
||||||
|
== JDK AOT cache, training with the same 300-request warm-up
|
||||||
|
training took 15222 ms; 68 MB
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
== 1. A file opened in a constructor and never closed (profile 'leaky'), checkpoint at start-up
|
||||||
|
java exit code: 1
|
||||||
|
WARN 11231 --- [crac-demo] [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to take CRaC checkpoint on refresh
|
||||||
|
ERROR 11231 --- [crac-demo] [ main] o.s.boot.SpringApplication : Application run failed
|
||||||
|
org.springframework.context.ApplicationContextException: Failed to take CRaC checkpoint on refresh
|
||||||
|
Caused by: org.crac.CheckpointException
|
||||||
|
Suppressed: jdk.internal.crac.mirror.impl.CheckpointOpenFileException: <work>/audit.log
|
||||||
|
checkpoint directory exists: no
|
||||||
|
|
||||||
|
== 2. The same mistake, checkpoint requested later with jcmd JDK.checkpoint
|
||||||
|
11275:
|
||||||
|
An exception during a checkpoint operation:
|
||||||
|
jdk.internal.crac.mirror.CheckpointException
|
||||||
|
Suppressed: jdk.internal.crac.mirror.impl.CheckpointOpenFileException: <work>/audit.log
|
||||||
|
at java.base/jdk.internal.crac.JDKFileResource.lambda$beforeCheckpoint$0(JDKFileResource.java:134)
|
||||||
|
at java.base/jdk.internal.crac.mirror.Core.checkpointRestore1(Core.java:195)
|
||||||
|
at java.base/jdk.internal.crac.mirror.Core.checkpointRestore(Core.java:291)
|
||||||
|
at java.base/jdk.internal.crac.mirror.Core.checkpointRestoreInternal(Core.java:327)
|
||||||
|
application still running and answering: pong
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
== 3. The fix: open in start(), close in stop() (profile 'managed'), checkpoint with jcmd, restore
|
||||||
|
orders before checkpoint; audit file has 3 lines
|
||||||
|
--- log of the checkpointed process (hooks only)
|
||||||
|
INFO 11435 --- [crac-demo] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 18771 (http)
|
||||||
|
INFO 11435 --- [crac-demo] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
|
||||||
|
INFO 11435 --- [crac-demo] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/11.0.27]
|
||||||
|
INFO 11435 --- [crac-demo] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 18771 (http) with context path '/'
|
||||||
|
ManagedAuditLog: opened <work>/audit.log
|
||||||
|
INFO 11435 --- [crac-demo] [io-18771-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
|
||||||
|
ManagedAuditLog: closed <work>/audit.log
|
||||||
|
RestoreTracker: beforeCheckpoint
|
||||||
|
--- log of the restored process (hooks only)
|
||||||
|
RestoreTracker: afterRestore (restore #1)
|
||||||
|
INFO 11435 --- [crac-demo] [Attach Listener] o.s.c.support.DefaultLifecycleProcessor : Restarting Spring-managed lifecycle beans after JVM restore
|
||||||
|
INFO 11435 --- [crac-demo] [Attach Listener] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 18771 (http) with context path '/'
|
||||||
|
ManagedAuditLog: opened <work>/audit.log
|
||||||
|
INFO 11435 --- [crac-demo] [Attach Listener] o.s.c.support.DefaultLifecycleProcessor : Spring-managed lifecycle restart completed (restored JVM running for 93 ms)
|
||||||
|
--- after restore: new order (id continues from the checkpointed counter), audit file now has 4 lines:
|
||||||
|
{"id":4,"customer":"ada","sku":"X","quantity":1}
|
||||||
|
created order 1
|
||||||
|
created order 2
|
||||||
|
created order 3
|
||||||
|
created order 4
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
== 4. Environment variables and secrets
|
||||||
|
before checkpoint: {"pid":11657,"restores":0,"greetingAtStartup":"value-at-checkpoint-S3CRET-7f3a91","greetingNow":"value-at-checkpoint-S3CRET-7f3a91","jvmUptimeMs":3954}
|
||||||
|
restored with DEMO_GREETING=value-at-restore:
|
||||||
|
after restore: {"pid":11791,"restores":1,"greetingAtStartup":"value-at-checkpoint-S3CRET-7f3a91","greetingNow":"value-at-restore","jvmUptimeMs":123}
|
||||||
|
occurrences of the checkpoint-time value in core.img: 4
|
||||||
|
checkpoint file mode: 600 root
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
files in the JDK's lib directory that belong to CRaC:
|
||||||
|
criu
|
||||||
|
criuhelper
|
||||||
|
libcriuengine.so
|
||||||
|
libsimengine.so
|
||||||
|
libwarp.so
|
||||||
|
|
||||||
|
== the same flag on the stock Temurin 25 JDK
|
||||||
|
Unrecognized VM option 'CRaCCheckpointTo=<work>/cp-temurin'
|
||||||
|
Error: Could not create the Java Virtual Machine.
|
||||||
|
Error: A fatal exception has occurred. Program will exit.
|
||||||
|
|
||||||
|
engine recorded in the default checkpoint (cp-refresh/engine): warp
|
||||||
|
process capabilities (CapEff): 000001fffeffffff, uid 0
|
||||||
|
|
||||||
|
== -XX:CRaCEngine=warp, checkpoint at start-up then restore
|
||||||
|
checkpoint directory: core.img engine (2 files); size: 129 MB
|
||||||
|
RestoreTracker: beforeCheckpoint
|
||||||
|
[4.243s][info][crac] Checkpoint ...
|
||||||
|
4184.436746: warp: Checkpoint 24528 to <work>/cp-eng-warp
|
||||||
|
4184.499576: warp: error: Cannot reset arguments to (-->)00007ffcab2bd075-00007ffcab2bd166: Operation not permitted
|
||||||
|
4184.499614: warp: error: Cannot reset arguments to 00007ffcab2bd075-00007ffcab2bd166(<--): Operation not permitted
|
||||||
|
4184.500952: warp: Checkpoint successful!
|
||||||
|
restored; GET /ping -> pong; Restored CracDemoApplication in 0.251 seconds (process running for 0.256)
|
||||||
|
|
||||||
|
== -XX:CRaCEngine=criuengine, checkpoint at start-up then restore
|
||||||
|
checkpoint directory: core-24639.img core-24641.img core-24642.img (39 files); size: 112 MB
|
||||||
|
RestoreTracker: beforeCheckpoint
|
||||||
|
[3.535s][info][crac] Checkpoint ...
|
||||||
|
restored; GET /ping -> pong; Restored CracDemoApplication in 0.183 seconds (process running for 0.184)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
build wall time: 834 s (mvn -Pnative -DskipTests native:compile, measured around the whole Maven run, 2 vCPU shared with other jobs)
|
||||||
|
[1/8] Initializing... (16.0s @ 0.17GB)
|
||||||
|
Java version: 25.0.4+7-LTS, vendor version: Oracle GraalVM 25.0.4+7.1
|
||||||
|
Graal compiler: optimization level: 2, target machine: x86-64-v3, PGO: ML-inferred
|
||||||
|
Garbage collector: Serial GC (max heap size: 80% of RAM)
|
||||||
|
[2/8] Performing analysis... [*****] (173.6s @ 2.02GB)
|
||||||
|
22,195 types, 31,358 fields, and 109,350 methods found reachable
|
||||||
|
8,538 types, 5,070 fields, and 22,270 methods registered for reflection
|
||||||
|
68 types, 71 fields, and 58 methods registered for JNI access
|
||||||
|
[3/8] Building universe... (19.2s @ 2.34GB)
|
||||||
|
[4/8] Parsing methods... [********] (72.7s @ 2.58GB)
|
||||||
|
[5/8] Inlining methods... [***] (9.1s @ 2.76GB)
|
||||||
|
[6/8] Compiling methods... [*********************] (461.3s @ 3.28GB)
|
||||||
|
[7/8] Laying out methods... [*****] (26.6s @ 3.10GB)
|
||||||
|
[8/8] Creating image... [***] (11.6s @ 3.43GB)
|
||||||
|
94.7s (11.8% of total time) in 3046 GCs | Peak RSS: 4.99GB | CPU load: 1.31
|
||||||
|
Finished generating 'crac-demo' in 13m 17s.
|
||||||
|
binary size: 99 MB (target/crac-demo, plus 6 small .so shims)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
rounds: 10 load average before: 0.80 0.94 2.53 cpus: 2
|
||||||
|
configuration ready ms (median [min..max]) 1st POST ms next 50 ms RSS MB
|
||||||
|
plain-temurin 3973 [3517..4290] 138.7 2.28 184
|
||||||
|
plain-zulu-crac 3847 [3378..4270] 129.7 2.57 186
|
||||||
|
aot-ctx-only 2186 [1890..2457] 121.6 2.43 193
|
||||||
|
aot-traffic 2077 [1944..2323] 65.0 3.59 192
|
||||||
|
crac-on-refresh 430 [395..540] 211.3 3.21 170
|
||||||
|
crac-warm 108 [93..153] 12.1 1.95 152
|
||||||
|
native 86 [83..118] 3.3 0.40 98
|
||||||
|
raw ready ms per round:
|
||||||
|
plain-temurin: 3517 4156 3996 4093 3993 3890 3953 4290 3723 3807
|
||||||
|
plain-zulu-crac: 3984 3802 3951 3869 4089 4270 3749 3805 3378 3824
|
||||||
|
aot-ctx-only: 1890 2240 2214 2158 2030 1979 2457 2268 2039 2307
|
||||||
|
aot-traffic: 2081 2053 1944 2012 2090 2072 2125 1973 2110 2323
|
||||||
|
crac-on-refresh: 407 428 399 540 448 395 452 437 432 421
|
||||||
|
crac-warm: 107 109 104 153 93 98 117 104 109 122
|
||||||
|
native: 90 94 86 87 117 83 118 86 83 85
|
||||||
|
load average after: 2.22 1.62 2.54
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
ready (ms) after dropping the page cache, 5 rounds, interleaved:
|
||||||
|
plain-temurin: 4462 4196 4304 4342 4091
|
||||||
|
aot-traffic: 2217 2110 2052 2319 2149
|
||||||
|
crac-warm: 257 255 207 221 247
|
||||||
|
native: 216 251 193 249 204
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>4.2.0</version>
|
||||||
|
<relativePath/>
|
||||||
|
</parent>
|
||||||
|
<groupId>com.ankurm</groupId>
|
||||||
|
<artifactId>crac-demo</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>crac-demo</name>
|
||||||
|
<description>One small Spring Boot service started five ways: plain JVM, JDK AOT cache, CRaC checkpoint/restore, native image</description>
|
||||||
|
<properties>
|
||||||
|
<java.version>25</java.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- Spring's CRaC support is switched on by this jar being on the class path (version managed by Boot 4.2: 1.5.0). -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.crac</groupId>
|
||||||
|
<artifactId>crac</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Interleaved rounds of every start-up configuration; "ready" = spawn -> first HTTP 200 from GET /ping.
|
||||||
|
# Needs: build.sh, native.sh, checkpoints.sh already run. Usage: ./scripts/bench.sh [rounds]
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
R="${1:-10}"
|
||||||
|
{ echo "rounds: $R load average before: $(cut -d' ' -f1-3 /proc/loadavg) cpus: $(nproc)"; $TOOL bench "$R" 2>/dev/null; echo "load average after: $(cut -d' ' -f1-3 /proc/loadavg)"; } | tee "$OUT/08-bench.txt"
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build the jar once and extract it to the layout every start-up variant uses.
|
||||||
|
set -euo pipefail
|
||||||
|
source "$(dirname "$0")/env.sh"
|
||||||
|
cd "$ROOT"
|
||||||
|
JAVA_HOME="$JDK_PLAIN" PATH="$JDK_PLAIN/bin:$PATH" mvn -B -q -DskipTests clean package
|
||||||
|
rm -rf "$WORK/app"
|
||||||
|
run_env "$JDK_PLAIN/bin/java" -Djarmode=tools -jar target/crac-demo-1.0.0.jar extract --destination "$WORK/app"
|
||||||
|
ls -la "$WORK/app"
|
||||||
Executable
+35
@@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Creates the checkpoints and AOT caches the benchmark restores/uses, and records what it cost.
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
cd "$WORK"; : > "$OUT/02-create.txt"
|
||||||
|
say() { echo "$@" | tee -a "$OUT/02-create.txt"; }
|
||||||
|
|
||||||
|
say "== CRaC checkpoint at start-up (-Dspring.context.checkpoint=onRefresh)"
|
||||||
|
rm -rf cp-refresh; t0=$(now_ms)
|
||||||
|
run_env "$JDK_CRAC/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-refresh" -Dspring.context.checkpoint=onRefresh -jar "$APPJAR" --server.port=$PORT > refresh.log 2>&1 || true
|
||||||
|
t1=$(now_ms)
|
||||||
|
say "process exited after $((t1-t0)) ms; checkpoint dir: $(ls cp-refresh | tr '\n' ' ') size: $(du_mb cp-refresh) MB"
|
||||||
|
grep -E 'Starting CracDemo|Checkpoint|warp: Checkpoint' refresh.log | grep -v 'always available' | scrub | tee -a "$OUT/02-create.txt"
|
||||||
|
|
||||||
|
say; say "== CRaC checkpoint after warm-up (300 POST + 300 GET, then jcmd JDK.checkpoint)"
|
||||||
|
rm -rf cp-warm
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$JDK_CRAC/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-warm" -jar "$APPJAR" --server.port=$PORT > warm.log 2>&1 < /dev/null &
|
||||||
|
wait_ready || { say "app did not start"; exit 1; }
|
||||||
|
PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-warm" | head -1)
|
||||||
|
$TOOL traffic "$PORT" 300
|
||||||
|
t0=$(now_ms); run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > jcmd.log 2>&1 || true; t1=$(now_ms)
|
||||||
|
wait_exit "$PID"; t2=$(now_ms)
|
||||||
|
say "jcmd JDK.checkpoint returned after $((t1-t0)) ms; process gone after $((t2-t0)) ms; checkpoint size: $(du_mb cp-warm) MB"
|
||||||
|
grep -E 'Spring-managed|Checkpoint|checkpoint|warp: Checkpoint' warm.log | scrub | tee -a "$OUT/02-create.txt"
|
||||||
|
|
||||||
|
say; say "== JDK AOT cache (JEP 514), context-only training"
|
||||||
|
rm -f ctx.aot; t0=$(now_ms)
|
||||||
|
run_env "$JDK_PLAIN/bin/java" -XX:AOTCacheOutput="$WORK/ctx.aot" -Dspring.context.exit=onRefresh -jar "$APPJAR" --server.port=$PORT > aot-ctx.log 2>&1
|
||||||
|
say "training took $(( $(now_ms)-t0 )) ms; $(ls -l ctx.aot | awk '{printf "%.0f MB", $5/1048576}')"
|
||||||
|
|
||||||
|
say; say "== JDK AOT cache, training with the same 300-request warm-up"
|
||||||
|
rm -f traffic.aot
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$JDK_PLAIN/bin/java" -XX:AOTCacheOutput="$WORK/traffic.aot" -jar "$APPJAR" --server.port=$PORT > aot-traffic.log 2>&1 < /dev/null &
|
||||||
|
t0=$(now_ms); wait_ready; PID=$(pgrep -f "AOTCacheOutput=$WORK/traffic.aot" | head -1)
|
||||||
|
$TOOL traffic "$PORT" 300; kill -TERM "$PID"; wait_exit "$PID"
|
||||||
|
say "training took $(( $(now_ms)-t0 )) ms; $(ls -l traffic.aot | awk '{printf "%.0f MB", $5/1048576}')"
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# One start per configuration with the Linux page cache emptied first (a freshly pulled container image or a freshly scheduled pod).
|
||||||
|
# 5 repetitions each, interleaved. Needs root (writes /proc/sys/vm/drop_caches).
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
R="${1:-5}"
|
||||||
|
declare -A res
|
||||||
|
for r in $(seq 1 "$R"); do
|
||||||
|
for c in plain-temurin aot-traffic crac-warm native; do
|
||||||
|
sync; echo 3 > /proc/sys/vm/drop_caches
|
||||||
|
v=$($TOOL once "$c" | python3 -c 'import json,sys; print(round(json.load(sys.stdin)["ready"]))')
|
||||||
|
res[$c]="${res[$c]} $v"
|
||||||
|
done
|
||||||
|
done
|
||||||
|
{ echo "ready (ms) after dropping the page cache, $R rounds, interleaved:"; for c in plain-temurin aot-traffic crac-warm native; do echo " $c:${res[$c]}"; done; } | tee "$OUT/09-cold-cache.txt"
|
||||||
Executable
+135
@@ -0,0 +1,135 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Measurement helper for the CRaC post. Standard library only.
|
||||||
|
|
||||||
|
crac_tool.py bench ROUNDS interleaved rounds of every configuration, prints a table
|
||||||
|
crac_tool.py once LABEL start one configuration, print time to first 200 and first POST
|
||||||
|
crac_tool.py traffic PORT N send N valid POST /orders and GET /orders/{id} requests (warm-up)
|
||||||
|
|
||||||
|
"Ready" = milliseconds from the moment the process is spawned until the first HTTP 200 from GET /ping
|
||||||
|
(polled every 2 ms from a raw socket, so the poll itself costs almost nothing).
|
||||||
|
"""
|
||||||
|
import json, os, signal, socket, statistics, subprocess, sys, time
|
||||||
|
|
||||||
|
ENV = {k: v for k, v in os.environ.items() if k not in ("JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS")}
|
||||||
|
W = os.environ.get("WORK", "/tmp/crac-work")
|
||||||
|
PORT = int(os.environ.get("PORT", "18771"))
|
||||||
|
JDK_PLAIN, JDK_CRAC = os.environ["JDK_PLAIN"], os.environ["JDK_CRAC"]
|
||||||
|
APP = f"{W}/app/crac-demo-1.0.0.jar"
|
||||||
|
|
||||||
|
CONFIGS = {
|
||||||
|
"plain-temurin": [f"{JDK_PLAIN}/bin/java", "-jar", APP, f"--server.port={PORT}"],
|
||||||
|
"plain-zulu-crac": [f"{JDK_CRAC}/bin/java", "-jar", APP, f"--server.port={PORT}"],
|
||||||
|
"aot-ctx-only": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/ctx.aot", "-jar", APP, f"--server.port={PORT}"],
|
||||||
|
"aot-traffic": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/traffic.aot", "-jar", APP, f"--server.port={PORT}"],
|
||||||
|
"crac-on-refresh": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-refresh"],
|
||||||
|
"crac-warm": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-warm"],
|
||||||
|
"native": [f"{W}/native/crac-demo", f"--server.port={PORT}"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def http(method, path, body=None, timeout=5.0):
|
||||||
|
s = socket.create_connection(("127.0.0.1", PORT), timeout=timeout)
|
||||||
|
try:
|
||||||
|
data = json.dumps(body).encode() if body is not None else b""
|
||||||
|
hdr = f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"
|
||||||
|
if body is not None:
|
||||||
|
hdr += f"Content-Type: application/json\r\nContent-Length: {len(data)}\r\n"
|
||||||
|
s.sendall(hdr.encode() + b"\r\n" + data)
|
||||||
|
buf = b""
|
||||||
|
while True:
|
||||||
|
c = s.recv(65536)
|
||||||
|
if not c: break
|
||||||
|
buf += c
|
||||||
|
return int(buf.split(b" ", 2)[1]), buf.split(b"\r\n\r\n", 1)[1].decode()
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
def port_free():
|
||||||
|
s = socket.socket()
|
||||||
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # TIME_WAIT sockets from the last run must not count as busy
|
||||||
|
try:
|
||||||
|
s.bind(("127.0.0.1", PORT)); return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
def session_rss_mb(sid):
|
||||||
|
best = 0
|
||||||
|
for pid in os.listdir("/proc"):
|
||||||
|
if not pid.isdigit(): continue
|
||||||
|
try:
|
||||||
|
if os.getsid(int(pid)) != sid: continue
|
||||||
|
for line in open(f"/proc/{pid}/status"):
|
||||||
|
if line.startswith("VmRSS:"):
|
||||||
|
best = max(best, int(line.split()[1]) // 1024)
|
||||||
|
except (OSError, ProcessLookupError):
|
||||||
|
pass
|
||||||
|
return best
|
||||||
|
|
||||||
|
def run(label, log=None):
|
||||||
|
assert port_free(), "port busy"
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
p = subprocess.Popen(CONFIGS[label], env=ENV, cwd=W, start_new_session=True,
|
||||||
|
stdout=open(log or os.devnull, "w"), stderr=subprocess.STDOUT)
|
||||||
|
ready = None
|
||||||
|
while time.perf_counter() - t0 < 60:
|
||||||
|
try:
|
||||||
|
st, _ = http("GET", "/ping", timeout=1)
|
||||||
|
if st == 200:
|
||||||
|
ready = (time.perf_counter() - t0) * 1000; break
|
||||||
|
except OSError:
|
||||||
|
time.sleep(0.002)
|
||||||
|
if ready is None:
|
||||||
|
kill(p); raise RuntimeError(label + ": not ready")
|
||||||
|
t1 = time.perf_counter()
|
||||||
|
st, _ = http("POST", "/orders", {"customer": "ada", "sku": "X-1", "quantity": 2})
|
||||||
|
first_post = (time.perf_counter() - t1) * 1000
|
||||||
|
assert st == 201, st
|
||||||
|
times = []
|
||||||
|
for i in range(50):
|
||||||
|
t = time.perf_counter(); http("GET", "/orders/1"); times.append((time.perf_counter() - t) * 1000)
|
||||||
|
rss = session_rss_mb(p.pid)
|
||||||
|
kill(p)
|
||||||
|
return dict(ready=ready, first_post=first_post, next50=statistics.median(times), rss=rss)
|
||||||
|
|
||||||
|
def kill(p):
|
||||||
|
try: os.killpg(p.pid, signal.SIGKILL)
|
||||||
|
except ProcessLookupError: pass
|
||||||
|
try: p.wait(5)
|
||||||
|
except Exception: pass
|
||||||
|
for _ in range(500):
|
||||||
|
if port_free(): return
|
||||||
|
time.sleep(0.01)
|
||||||
|
|
||||||
|
def bench(rounds):
|
||||||
|
res = {k: [] for k in CONFIGS}
|
||||||
|
for r in range(rounds):
|
||||||
|
for k in CONFIGS:
|
||||||
|
res[k].append(run(k)); time.sleep(0.3)
|
||||||
|
print(f"round {r+1}/{rounds} done", file=sys.stderr)
|
||||||
|
print(f"{'configuration':<18}{'ready ms (median [min..max])':<34}{'1st POST ms':>12}{'next 50 ms':>12}{'RSS MB':>8}")
|
||||||
|
for k, rs in res.items():
|
||||||
|
rd = [x["ready"] for x in rs]
|
||||||
|
print(f"{k:<18}{statistics.median(rd):>8.0f} [{min(rd):.0f}..{max(rd):.0f}]".ljust(52)
|
||||||
|
+ f"{statistics.median(x['first_post'] for x in rs):>12.1f}"
|
||||||
|
+ f"{statistics.median(x['next50'] for x in rs):>12.2f}"
|
||||||
|
+ f"{statistics.median(x['rss'] for x in rs):>8.0f}")
|
||||||
|
print("raw ready ms per round:")
|
||||||
|
for k, rs in res.items():
|
||||||
|
print(f" {k}: " + " ".join(f"{x['ready']:.0f}" for x in rs))
|
||||||
|
|
||||||
|
def traffic(n):
|
||||||
|
for i in range(n):
|
||||||
|
st, body = http("POST", "/orders", {"customer": f"c{i%7}", "sku": f"S-{i%13}", "quantity": 1 + i % 5})
|
||||||
|
assert st == 201, (st, body)
|
||||||
|
http("GET", f"/orders/{i+1}")
|
||||||
|
http("POST", "/orders", {"customer": "", "sku": "X", "quantity": 0}) # a 400, so the validation error path is warm
|
||||||
|
http("GET", "/orders/999999") # a 404
|
||||||
|
http("GET", "/actuator/health")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
cmd = sys.argv[1]
|
||||||
|
if cmd == "bench": bench(int(sys.argv[2]))
|
||||||
|
elif cmd == "once": print(json.dumps(run(sys.argv[2], f"{W}/once-{sys.argv[2]}.log")))
|
||||||
|
elif cmd == "traffic":
|
||||||
|
PORT = int(sys.argv[2]); traffic(int(sys.argv[3]))
|
||||||
Executable
+25
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# The Zulu 25 CRaC JVM ships more than one engine. Which one ran above, and does the CRIU one work in this sandbox?
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
cd "$WORK"; J="$JDK_CRAC/bin/java"; : > "$OUT/06-engines.txt"
|
||||||
|
say() { echo "$@" | tee -a "$OUT/06-engines.txt"; }
|
||||||
|
say "files in the JDK's lib directory that belong to CRaC:"; ls "$JDK_CRAC/lib" | grep -i -E 'criu|crac|warp|engine' | sed 's/^/ /' | tee -a "$OUT/06-engines.txt"
|
||||||
|
say; say "== the same flag on the stock Temurin 25 JDK"
|
||||||
|
run_env "$JDK_PLAIN/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-temurin" -version 2>&1 | head -3 | scrub | tee -a "$OUT/06-engines.txt"
|
||||||
|
say; say "engine recorded in the default checkpoint (cp-refresh/engine): $(cat cp-refresh/engine 2>/dev/null)"
|
||||||
|
say "process capabilities (CapEff): $(grep CapEff /proc/self/status | awk '{print $2}'), uid $(id -u)"
|
||||||
|
for ENG in warp criuengine; do
|
||||||
|
say; say "== -XX:CRaCEngine=$ENG, checkpoint at start-up then restore"
|
||||||
|
rm -rf "cp-eng-$ENG"
|
||||||
|
# CRIU is picky about the process it dumps: a regular file open as stdout must not change size before the restore ("has bad size"),
|
||||||
|
# a stdin that is a socket fails the dump ("External socket is used"), and a JVM that is not its own session leader cannot be restored
|
||||||
|
# ("Current gid ... intersects with pid ... in images"). So: new session (setsid), stdin /dev/null, stdout through a pipe (cat).
|
||||||
|
setsid --wait bash -c "env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS '$J' -XX:CRaCEngine=$ENG -XX:CRaCCheckpointTo='$WORK/cp-eng-$ENG' -Dspring.context.checkpoint=onRefresh -jar '$APPJAR' --server.port=$PORT 2>&1 | cat > 'eng-$ENG-1.log'" < /dev/null
|
||||||
|
say "checkpoint directory: $(ls cp-eng-$ENG 2>/dev/null | head -3 | tr "\n" " ")($(ls cp-eng-$ENG | wc -l) files); size: $(du -sm cp-eng-$ENG 2>/dev/null | cut -f1) MB"
|
||||||
|
grep -E 'warp:|criu|CRIU|Error|error:|Checkpoint' "eng-$ENG-1.log" | grep -v 'always available' | scrub | head -8 | tee -a "$OUT/06-engines.txt"
|
||||||
|
if [ -d "cp-eng-$ENG" ]; then
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCEngine=$ENG -XX:CRaCRestoreFrom="$WORK/cp-eng-$ENG" > "eng-$ENG-2.log" 2>&1 < /dev/null &
|
||||||
|
if wait_ready; then say "restored; GET /ping -> $(curl -s localhost:$PORT/ping); $(grep -E 'Restored CracDemo' eng-$ENG-2.log | scrub | sed -E 's/.*: //')"; else say "restore did not become ready"; grep -v '^$' "eng-$ENG-2.log" | scrub | head -6 | tee -a "$OUT/06-engines.txt"; fi
|
||||||
|
stop_port
|
||||||
|
fi
|
||||||
|
done
|
||||||
Executable
+13
@@ -0,0 +1,13 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Where the JDKs live. Override on the command line, e.g. JDK_CRAC=/opt/zulu-crac ./scripts/run-all.sh
|
||||||
|
export JDK_PLAIN="${JDK_PLAIN:-/tmp/tools/tem/jdk-25.0.5.1+2}" # Temurin 25.0.5.1 (plain JVM, AOT cache)
|
||||||
|
export JDK_CRAC="${JDK_CRAC:-/tmp/tools/zulu/zulu25.38.203-ca-crac-jdk25.0.5.1.1-linux_x64}" # Azul Zulu 25 with CRaC
|
||||||
|
export JDK_GRAAL="${JDK_GRAAL:-/tmp/tools/graal/graalvm-jdk-25.0.4+7.1}" # Oracle GraalVM 25.0.4 (native-image)
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; export ROOT
|
||||||
|
export OUT="$ROOT/output"; mkdir -p "$OUT"
|
||||||
|
export WORK="${WORK:-/tmp/crac-work}"; mkdir -p "$WORK" # checkpoints, caches, logs: not committed
|
||||||
|
export PORT="${PORT:-18771}"
|
||||||
|
# The JVM prints "Picked up JAVA_TOOL_OPTIONS" on every launch in some sandboxes; it is noise in a transcript.
|
||||||
|
# (Maven itself needs the variable in such a sandbox, so only the run scripts clear it, never build.sh.)
|
||||||
|
run_env() { env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$@"; }
|
||||||
|
export TOOL="python3 $ROOT/scripts/crac_tool.py"; export JDK_PLAIN JDK_CRAC WORK PORT
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# shared helpers (sourced)
|
||||||
|
source "$(dirname "${BASH_SOURCE[0]}")/env.sh"
|
||||||
|
APPJAR="$WORK/app/crac-demo-1.0.0.jar"
|
||||||
|
wait_ready() { for i in $(seq 1 600); do curl -s -o /dev/null "localhost:$PORT/ping" && return 0; sleep 0.1; done; return 1; }
|
||||||
|
wait_exit() { for i in $(seq 1 600); do kill -0 "$1" 2>/dev/null || return 0; sleep 0.1; done; return 1; }
|
||||||
|
now_ms() { echo $(( $(date +%s%N) / 1000000 )); }
|
||||||
|
du_mb() { du -sm "$1" | cut -f1; }
|
||||||
|
# keep transcripts free of machine paths and wall-clock dates
|
||||||
|
scrub() { sed -E "s#$WORK#<work>#g; s#$ROOT#<repo>#g; s#/tmp/tools/[^ /]*/[^ /]*#<jdk>#g; s#^[0-9T:.+-]{29} ##"; }
|
||||||
|
stop_port() { fuser -k -9 "$PORT/tcp" >/dev/null 2>&1; sleep 0.5; } # kills whatever listens on our (private) port
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Builds the native image with Oracle GraalVM 25 (about 5 to 14 minutes on 2 vCPU; 5 GB peak) and records the build summary.
|
||||||
|
source "$(dirname "$0")/env.sh"
|
||||||
|
cd "$ROOT"
|
||||||
|
S=$(date +%s)
|
||||||
|
JAVA_HOME="$JDK_GRAAL" PATH="$JDK_GRAAL/bin:$PATH" mvn -B -Pnative -DskipTests native:compile > "$WORK/native-build.log" 2>&1
|
||||||
|
E=$(( $(date +%s) - S ))
|
||||||
|
mkdir -p "$WORK/native"; cp target/crac-demo "$WORK/native/"
|
||||||
|
{ echo "build wall time: ${E} s "; grep -E '^\[[0-9]/8\]|Finished generating|Peak RSS|in .* GCs|types, |Garbage collector|target machine' "$WORK/native-build.log" | sed -E 's/ {3,}/ /g';
|
||||||
|
echo "binary size: $(du -m "$WORK/native/crac-demo" | cut -f1) MB"; } | tee "$OUT/07-native-build.txt"
|
||||||
Executable
+55
@@ -0,0 +1,55 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# What happens to open files, environment variables and secrets across a checkpoint.
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
cd "$WORK"; stop_port
|
||||||
|
AUDIT="$WORK/audit.log"
|
||||||
|
J="$JDK_CRAC/bin/java"
|
||||||
|
|
||||||
|
echo "== 1. A file opened in a constructor and never closed (profile 'leaky'), checkpoint at start-up" | tee "$OUT/03-leaky.txt"
|
||||||
|
rm -rf cp-leaky "$AUDIT"
|
||||||
|
run_env "$J" -XX:CRaCCheckpointTo="$WORK/cp-leaky" -Dspring.context.checkpoint=onRefresh -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=leaky --demo.audit-file="$AUDIT" > leaky.log 2>&1
|
||||||
|
echo "java exit code: $?" | tee -a "$OUT/03-leaky.txt"
|
||||||
|
grep -E 'ERROR|ApplicationContextException|Caused by|CheckpointOpenFileException|Suppressed' leaky.log | scrub | tee -a "$OUT/03-leaky.txt"
|
||||||
|
echo "checkpoint directory exists: $([ -d cp-leaky ] && echo yes || echo no)" | tee -a "$OUT/03-leaky.txt"
|
||||||
|
|
||||||
|
echo | tee -a "$OUT/03-leaky.txt"; echo "== 2. The same mistake, checkpoint requested later with jcmd JDK.checkpoint" | tee -a "$OUT/03-leaky.txt"
|
||||||
|
rm -rf cp-leaky2 "$AUDIT"
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCCheckpointTo="$WORK/cp-leaky2" -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=leaky --demo.audit-file="$AUDIT" > leaky2.log 2>&1 < /dev/null &
|
||||||
|
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-leaky2" | head -1)
|
||||||
|
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint 2>&1 | grep -v '^$' | scrub | head -8 | tee -a "$OUT/03-leaky.txt"
|
||||||
|
sleep 1
|
||||||
|
echo "application still running and answering: $(curl -s localhost:$PORT/ping)" | tee -a "$OUT/03-leaky.txt"
|
||||||
|
kill -9 "$PID"; wait_exit "$PID"
|
||||||
|
|
||||||
|
echo "== 3. The fix: open in start(), close in stop() (profile 'managed'), checkpoint with jcmd, restore" | tee "$OUT/04-managed.txt"
|
||||||
|
rm -rf cp-managed "$AUDIT"
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCCheckpointTo="$WORK/cp-managed" -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=managed --demo.audit-file="$AUDIT" > managed1.log 2>&1 < /dev/null &
|
||||||
|
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-managed" | head -1)
|
||||||
|
for i in 1 2 3; do curl -s -o /dev/null -X POST -H 'Content-Type: application/json' -d '{"customer":"ada","sku":"X","quantity":1}' localhost:$PORT/orders; done
|
||||||
|
echo "orders before checkpoint; audit file has $(wc -l < "$AUDIT") lines" | tee -a "$OUT/04-managed.txt"
|
||||||
|
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > /dev/null 2>&1; wait_exit "$PID"
|
||||||
|
echo "--- log of the checkpointed process (hooks only)" | tee -a "$OUT/04-managed.txt"
|
||||||
|
grep -E 'ManagedAuditLog|RestoreTracker|Spring-managed|Stopping|Tomcat' managed1.log | scrub | tee -a "$OUT/04-managed.txt"
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCRestoreFrom="$WORK/cp-managed" > managed2.log 2>&1 < /dev/null &
|
||||||
|
wait_ready; sleep 0.3
|
||||||
|
echo "--- log of the restored process (hooks only)" | tee -a "$OUT/04-managed.txt"
|
||||||
|
grep -E 'ManagedAuditLog|RestoreTracker|Spring-managed|Tomcat|Restored' managed2.log | scrub | tee -a "$OUT/04-managed.txt"
|
||||||
|
curl -s -o /dev/null -X POST -H 'Content-Type: application/json' -d '{"customer":"ada","sku":"X","quantity":1}' localhost:$PORT/orders
|
||||||
|
echo "--- after restore: new order (id continues from the checkpointed counter), audit file now has $(wc -l < "$AUDIT") lines:" | tee -a "$OUT/04-managed.txt"
|
||||||
|
curl -s localhost:$PORT/orders/4 | tee -a "$OUT/04-managed.txt"; echo | tee -a "$OUT/04-managed.txt"
|
||||||
|
cat "$AUDIT" | tee -a "$OUT/04-managed.txt"
|
||||||
|
stop_port
|
||||||
|
|
||||||
|
echo "== 4. Environment variables and secrets" | tee "$OUT/05-environment.txt"
|
||||||
|
rm -rf cp-env
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS DEMO_GREETING=value-at-checkpoint-S3CRET-7f3a91 "$J" -XX:CRaCCheckpointTo="$WORK/cp-env" -jar "$APPJAR" --server.port=$PORT > env1.log 2>&1 < /dev/null &
|
||||||
|
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-env" | head -1)
|
||||||
|
echo "before checkpoint: $(curl -s localhost:$PORT/info)" | tee -a "$OUT/05-environment.txt"
|
||||||
|
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > /dev/null 2>&1; wait_exit "$PID"
|
||||||
|
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS DEMO_GREETING=value-at-restore "$J" -XX:CRaCRestoreFrom="$WORK/cp-env" > env2.log 2>&1 < /dev/null &
|
||||||
|
wait_ready
|
||||||
|
echo "restored with DEMO_GREETING=value-at-restore:" | tee -a "$OUT/05-environment.txt"
|
||||||
|
echo "after restore: $(curl -s localhost:$PORT/info)" | tee -a "$OUT/05-environment.txt"
|
||||||
|
echo "occurrences of the checkpoint-time value in core.img: $(grep -a -c 'value-at-checkpoint-S3CRET-7f3a91' cp-env/core.img)" | tee -a "$OUT/05-environment.txt"
|
||||||
|
echo "checkpoint file mode: $(stat -c '%a %U' cp-env/core.img)" | tee -a "$OUT/05-environment.txt"
|
||||||
|
stop_port
|
||||||
Executable
+13
@@ -0,0 +1,13 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file in output/. About 25 minutes on 2 vCPU (the native build alone is 5 to 14 minutes).
|
||||||
|
# Needs JDK_PLAIN, JDK_CRAC, JDK_GRAAL (see env.sh), Maven, Python 3, curl, and root for cold.sh.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
./build.sh
|
||||||
|
./native.sh
|
||||||
|
./versions.sh
|
||||||
|
./checkpoints.sh
|
||||||
|
./resources.sh
|
||||||
|
./engines.sh
|
||||||
|
./bench.sh 10
|
||||||
|
./cold.sh 5
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# What every number in the post was measured on.
|
||||||
|
source "$(dirname "$0")/lib.sh"
|
||||||
|
{
|
||||||
|
echo "== machine"; uname -sr; echo "cpus: $(nproc)"; free -m | awk 'NR==2{print "memory MB: "$2}'
|
||||||
|
echo; echo "== plain JVM and AOT cache"; run_env "$JDK_PLAIN/bin/java" -version 2>&1 | scrub
|
||||||
|
echo; echo "== CRaC JVM"; run_env "$JDK_CRAC/bin/java" -version 2>&1 | scrub
|
||||||
|
echo "engines shipped: $(ls "$JDK_CRAC/lib" | grep -E 'criu|libcriuengine|warp' | tr '\n' ' ')"
|
||||||
|
echo; echo "== native-image"; run_env "$JDK_GRAAL/bin/native-image" --version 2>&1 | scrub
|
||||||
|
echo; echo "== Spring"; unzip -p "$WORK/app/lib/spring-boot-4.2.0.jar" META-INF/MANIFEST.MF | grep -E 'Implementation-Version'
|
||||||
|
ls "$WORK/app/lib" | grep -E '^(spring-(core|context|webmvc|boot)-|crac-|tomcat-embed-core)'
|
||||||
|
} 2>&1 | tee "$OUT/01-versions.txt"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
/** Something that holds an operating-system resource (here: an open file). */
|
||||||
|
public interface AuditSink {
|
||||||
|
void write(String line);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
/** One small service used for every start-up measurement in the "CRaC vs AOT cache vs native image" post. */
|
||||||
|
@SpringBootApplication
|
||||||
|
public class CracDemoApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(CracDemoApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows what a restored process remembers. {@code greetingAtStartup} is read once in the constructor, {@code greetingNow} on every call:
|
||||||
|
* after a restore into a different environment the two differ, which is the "stale configuration" trap.
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
public class InfoController {
|
||||||
|
|
||||||
|
private final String greetingAtStartup = System.getenv().getOrDefault("DEMO_GREETING", "(unset)");
|
||||||
|
private final RestoreTracker tracker;
|
||||||
|
|
||||||
|
public InfoController(RestoreTracker tracker) {
|
||||||
|
this.tracker = tracker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/info")
|
||||||
|
public Map<String, Object> info() {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("pid", ProcessHandle.current().pid());
|
||||||
|
m.put("restores", tracker.restores());
|
||||||
|
m.put("greetingAtStartup", greetingAtStartup);
|
||||||
|
m.put("greetingNow", System.getenv().getOrDefault("DEMO_GREETING", "(unset)"));
|
||||||
|
m.put("jvmUptimeMs", ManagementFactory.getRuntimeMXBean().getUptime());
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mistake: a file is opened once and held for the life of the process.
|
||||||
|
* Active with {@code --spring.profiles.active=leaky}. A checkpoint taken while this file is open is the failure the post shows.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("leaky")
|
||||||
|
public class LeakyAuditLog implements AuditSink {
|
||||||
|
|
||||||
|
private final BufferedWriter out;
|
||||||
|
|
||||||
|
public LeakyAuditLog(@Value("${demo.audit-file:/tmp/crac-demo-audit.log}") Path file) throws IOException {
|
||||||
|
this.out = Files.newBufferedWriter(file, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized void write(String line) {
|
||||||
|
try {
|
||||||
|
out.write(line);
|
||||||
|
out.newLine();
|
||||||
|
out.flush();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.SmartLifecycle;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fix: the same file, opened in {@code start()} and closed in {@code stop()}. Spring calls {@code stop()} on every running
|
||||||
|
* lifecycle bean before a checkpoint and {@code start()} again after a restore, so no file is open while the process image is written.
|
||||||
|
* Active with {@code --spring.profiles.active=managed}.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("managed")
|
||||||
|
public class ManagedAuditLog implements AuditSink, SmartLifecycle {
|
||||||
|
|
||||||
|
private final Path file;
|
||||||
|
private BufferedWriter out;
|
||||||
|
|
||||||
|
public ManagedAuditLog(@Value("${demo.audit-file:/tmp/crac-demo-audit.log}") Path file) {
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized void start() {
|
||||||
|
try {
|
||||||
|
out = Files.newBufferedWriter(file, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||||
|
System.out.println("ManagedAuditLog: opened " + file);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized void stop() {
|
||||||
|
try {
|
||||||
|
if (out != null) {
|
||||||
|
out.close();
|
||||||
|
out = null;
|
||||||
|
System.out.println("ManagedAuditLog: closed " + file);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized boolean isRunning() {
|
||||||
|
return out != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized void write(String line) {
|
||||||
|
try {
|
||||||
|
out.write(line);
|
||||||
|
out.newLine();
|
||||||
|
out.flush();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/** Spring MVC + Jackson + Bean Validation, no database: enough classes to make start-up interesting. */
|
||||||
|
@RestController
|
||||||
|
public class OrderController {
|
||||||
|
|
||||||
|
public record OrderRequest(@NotBlank String customer, @NotBlank String sku, @Min(1) int quantity) {}
|
||||||
|
|
||||||
|
public record Order(long id, String customer, String sku, int quantity) {}
|
||||||
|
|
||||||
|
private final Map<Long, Order> store = new ConcurrentHashMap<>();
|
||||||
|
private final AtomicLong ids = new AtomicLong();
|
||||||
|
private final ObjectProvider<AuditSink> audit;
|
||||||
|
|
||||||
|
public OrderController(ObjectProvider<AuditSink> audit) {
|
||||||
|
this.audit = audit;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/ping")
|
||||||
|
public String ping() {
|
||||||
|
return "pong";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/orders")
|
||||||
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
|
public Order create(@Valid @RequestBody OrderRequest request) {
|
||||||
|
Order order = new Order(ids.incrementAndGet(), request.customer(), request.sku(), request.quantity());
|
||||||
|
store.put(order.id(), order);
|
||||||
|
audit.ifAvailable(a -> a.write("created order " + order.id()));
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/orders/{id}")
|
||||||
|
public Order get(@PathVariable long id) {
|
||||||
|
Order order = store.get(id);
|
||||||
|
if (order == null) {
|
||||||
|
throw new org.springframework.web.server.ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ankurm.crac;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.crac.Context;
|
||||||
|
import org.crac.Core;
|
||||||
|
import org.crac.Resource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plain org.crac API, for code that does not depend on Spring: a {@link Resource} registered with the global context is told
|
||||||
|
* before a checkpoint and after a restore. Here it only counts and logs, which is enough to prove the hooks run.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class RestoreTracker implements Resource {
|
||||||
|
|
||||||
|
private final AtomicInteger restores = new AtomicInteger();
|
||||||
|
|
||||||
|
public RestoreTracker() {
|
||||||
|
// The global context keeps only a weak reference, so this bean (a singleton) must stay strongly referenced elsewhere. Spring does that.
|
||||||
|
Core.getGlobalContext().register(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void beforeCheckpoint(Context<? extends Resource> context) {
|
||||||
|
System.out.println("RestoreTracker: beforeCheckpoint");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterRestore(Context<? extends Resource> context) {
|
||||||
|
System.out.println("RestoreTracker: afterRestore (restore #" + restores.incrementAndGet() + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int restores() {
|
||||||
|
return restores.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
spring.application.name=crac-demo
|
||||||
|
management.endpoints.web.exposure.include=health,info
|
||||||
|
spring.main.banner-mode=off
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
target/
|
||||||
|
*.class
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# gc-basics
|
||||||
|
|
||||||
|
Companion code for the ankurm.com article **"Java Garbage Collection Explained: How It Works and Which Collector to Choose (G1, ZGC, Shenandoah on JDK 25 to 28)"**
|
||||||
|
(<https://ankurm.com/a-developers-deep-dive-into-java-memory-management-and-garbage-collection/>).
|
||||||
|
|
||||||
|
No `docs/` folder: the explanation lives in the article, in collapsible sections. This module keeps only the sources, one script and the real output of every run.
|
||||||
|
|
||||||
|
| Thing | Version |
|
||||||
|
|---|---|
|
||||||
|
| JDK 25 (LTS) | Temurin 25.0.5.1+2 |
|
||||||
|
| JDK 27 | Temurin 27.0.1.1+4 (GA 2026-09-15) |
|
||||||
|
| JDK 28 | Temurin 28+25 early-access build 2026-11-19 (GA scheduled for March 2027, so anything seen only there may change) |
|
||||||
|
| Containers | `eclipse-temurin:25-jre`, `eclipse-temurin:27-jre` (step 22 only) |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
JDK25=/path/to/jdk-25 JDK27=/path/to/jdk-27 JDK28=/path/to/jdk-28 ./run.sh # regenerate every file in output/ (about 25 minutes)
|
||||||
|
./run.sh 07 15 # or just some steps
|
||||||
|
```
|
||||||
|
|
||||||
|
Timings (stalls, requests) depend on the machine; this was a 2 vCPU sandbox. Read them as shape, not as results. Everything else is stable.
|
||||||
|
|
||||||
|
## Sources (`src/`)
|
||||||
|
|
||||||
|
| File | What it shows |
|
||||||
|
|---|---|
|
||||||
|
| `Which.java` | which collector the JVM picked, read from the JVM's own `GarbageCollectorMXBean` names |
|
||||||
|
| `StackAndHeap.java`, `TryWithResources.java` | the two small snippets from the article |
|
||||||
|
| `Reach.java` | reachability observed with weak references: roots, a child, an unreferenced object, a two-object cycle |
|
||||||
|
| `Churn.java` | the workload: a live set (`flat` or `graph`) plus a stream of short-lived garbage, and a ticker thread that measures how late a 1 ms sleep wakes up |
|
||||||
|
| `SysGc.java` | what one `System.gc()` costs |
|
||||||
|
| `Leak.java` | a static collection that only grows, ending in `OutOfMemoryError` |
|
||||||
|
| `Finalize.java` | `finalize()` today: the compiler warning and `--finalization=disabled` |
|
||||||
|
|
||||||
|
## Captured output (`output/`)
|
||||||
|
|
||||||
|
| File | Step | What it is |
|
||||||
|
|---|---|---|
|
||||||
|
| `01` | `./run.sh 01` | default collector on JDK 25, 27, 28 for 1, 2 and 4 CPUs |
|
||||||
|
| `02` | `02` | `-XX:MaxRAM` on 25, 27, 28 |
|
||||||
|
| `03` | `03` | Shenandoah mode on 25, 27, 28 |
|
||||||
|
| `04` | `04` | ZGC: removed mode, flags new on 28 |
|
||||||
|
| `05` | `05` | reachability |
|
||||||
|
| `06` | `06` | reading a G1 log |
|
||||||
|
| `07` | `07` | five collectors, graph workload, 1 GB heap, three runs each |
|
||||||
|
| `08` | `08` | the default on 25, 27, 28 and Shenandoah on 28 |
|
||||||
|
| `09` | `09` | `jcmd GC.heap_info` per collector |
|
||||||
|
| `10` | `10` | `OutOfMemoryError` |
|
||||||
|
| `11` | `11` | `System.gc()` |
|
||||||
|
| `12` | `12` | `finalize()` |
|
||||||
|
| `13` | `13` | the two small snippets run |
|
||||||
|
| `14` | `14` | the flat live set baseline |
|
||||||
|
| `15` | `15` | G1 pause types |
|
||||||
|
| `16` | `16` | Native Memory Tracking |
|
||||||
|
| `17` | `17` | a few flag defaults |
|
||||||
|
| `18`, `20`, `21` | `18`, `20`, `21` | Shenandoah by JDK: stalls, pause types, allocation stalls |
|
||||||
|
| `19` | `19` | the same workload with a 2 GB heap |
|
||||||
|
| `22` | `22` | default collector under real `docker run --cpus --memory` limits |
|
||||||
|
|
||||||
|
MIT licensed, see the repository root.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
src/Finalize.java:13: warning: [removal] finalize() in Object has been deprecated and marked for removal
|
||||||
|
protected void finalize() { // deliberately not suppressed: javac prints a removal warning
|
||||||
|
^
|
||||||
|
1 warning
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
versions: OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS) | OpenJDK Runtime Environment Temurin-27.0.1.1+4 (build 27.0.1.1+4) | OpenJDK Runtime Environment Temurin-28+25-202611191755 (build 28-beta+25-ea)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Which collector does the JVM pick when you name none? (emulating a 1, 2 and 4 CPU machine with -XX:ActiveProcessorCount)
|
||||||
|
|
||||||
|
## JDK 25: OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
|
||||||
|
$ java -XX:ActiveProcessorCount=1 Which
|
||||||
|
collector MXBeans : Copy | MarkSweepCompact
|
||||||
|
$ java -XX:ActiveProcessorCount=2 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
$ java -XX:ActiveProcessorCount=4 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
|
||||||
|
## JDK 27: OpenJDK Runtime Environment Temurin-27.0.1.1+4 (build 27.0.1.1+4)
|
||||||
|
$ java -XX:ActiveProcessorCount=1 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
$ java -XX:ActiveProcessorCount=2 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
$ java -XX:ActiveProcessorCount=4 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
|
||||||
|
## JDK 28: OpenJDK Runtime Environment Temurin-28+25-202611191755 (build 28-beta+25-ea)
|
||||||
|
$ java -XX:ActiveProcessorCount=1 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
$ java -XX:ActiveProcessorCount=2 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
|
$ java -XX:ActiveProcessorCount=4 Which
|
||||||
|
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# The memory half of the rule cannot be emulated with -XX:MaxRAM on 27 or later
|
||||||
|
|
||||||
|
## JDK 25
|
||||||
|
$ java -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version | grep MaxRAM
|
||||||
|
uint64_t MaxRAM = 1073741824 {pd product} {command line}
|
||||||
|
|
||||||
|
## JDK 27
|
||||||
|
$ java -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version | grep MaxRAM
|
||||||
|
OpenJDK 64-Bit Server VM warning: Ignoring option MaxRAM; support was removed in 27.0
|
||||||
|
|
||||||
|
## JDK 28
|
||||||
|
$ java -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version | grep MaxRAM
|
||||||
|
Unrecognized VM option 'MaxRAM=1g'
|
||||||
|
Error: Could not create the Java Virtual Machine.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Shenandoah: which mode is the default, and is the generational mode still experimental? (mode read from -Xlog:gc+init)
|
||||||
|
|
||||||
|
## JDK 25, no mode flag
|
||||||
|
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
|
||||||
|
[0.008s][info][gc,init] Mode: Snapshot-At-The-Beginning (SATB)
|
||||||
|
|
||||||
|
## JDK 27, no mode flag
|
||||||
|
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
|
||||||
|
[0.007s][info][gc,init] Mode: Snapshot-At-The-Beginning (SATB)
|
||||||
|
|
||||||
|
## JDK 28, no mode flag
|
||||||
|
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
|
||||||
|
[0.014s][info][gc,init] Mode: generational
|
||||||
|
|
||||||
|
## JDK 25: generational mode without -XX:+UnlockExperimentalVMOptions
|
||||||
|
$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init -version
|
||||||
|
[0.011s][info][gc,init] Mode: Generational
|
||||||
|
|
||||||
|
## JDK 24-style spelling on 25 (the unlock flag is now unnecessary but harmless)
|
||||||
|
[0.012s][info][gc,init] Mode: Generational
|
||||||
|
|
||||||
|
## JDK 28 early access: asking for the old mode explicitly
|
||||||
|
$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xlog:gc+init -version
|
||||||
|
[0.007s][info][gc,init] Mode: satb
|
||||||
|
(no deprecation warning is printed by this early-access build)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# ZGC: the non-generational mode is gone, and what 28 adds
|
||||||
|
|
||||||
|
## JDK 25: ask for the old mode
|
||||||
|
$ java -XX:+UseZGC -XX:-ZGenerational -version
|
||||||
|
OpenJDK 64-Bit Server VM warning: Ignoring option ZGenerational; support was removed in 24.0
|
||||||
|
openjdk version "25.0.5.1" 2026-11-17 LTS
|
||||||
|
|
||||||
|
## JDK 25: plain ZGC
|
||||||
|
collector MXBeans : ZGC Minor Cycles | ZGC Minor Pauses | ZGC Major Cycles | ZGC Major Pauses
|
||||||
|
|
||||||
|
## ZGC flags present on 28 early access but not on 27 (diff of -XX:+PrintFlagsFinal -XX:+UseZGC, names only)
|
||||||
|
only on 28:
|
||||||
|
ZAdaptiveHeapSizing
|
||||||
|
ZGCIntensity
|
||||||
|
ZMemoryHeating
|
||||||
|
only on 27:
|
||||||
|
|
||||||
|
## its default on 28
|
||||||
|
size_t SoftMaxHeapSize = 1449551462 {manageable} {ergonomic}
|
||||||
|
bool ZAdaptiveHeapSizing = false {product} {default}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Reachability observed with weak references (JDK 25)
|
||||||
|
A (local variable) alive
|
||||||
|
B (static field) alive
|
||||||
|
C (child of A) alive
|
||||||
|
D (no references) collected
|
||||||
|
X (cycle with Y, no root) collected
|
||||||
|
Y (cycle with X, no root) collected
|
||||||
|
A and C are still used here: A -> C
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Reading a G1 log: the first lines of -Xlog:gc for the Churn workload (JDK 25, -Xms512m -Xmx512m, 150 MB live)
|
||||||
|
$ java -Xms512m -Xmx512m -Xlog:gc Churn 150 3
|
||||||
|
[0.004s][info][gc] Using G1
|
||||||
|
[0.044s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 26M->25M(512M) 12.661ms
|
||||||
|
[0.209s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 205M->164M(512M) 88.487ms
|
||||||
|
[0.244s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 283M->175M(512M) 17.136ms
|
||||||
|
[0.268s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 318M->176M(512M) 1.967ms
|
||||||
|
[0.298s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 340M->176M(512M) 2.303ms
|
||||||
|
[0.332s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 356M->176M(512M) 2.059ms
|
||||||
|
[0.386s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 387M->176M(512M) 10.611ms
|
||||||
|
[0.439s][info][gc] GC(7) Pause Young (Normal) (G1 Evacuation Pause) 407M->176M(512M) 10.162ms
|
||||||
|
[0.487s][info][gc] GC(8) Pause Young (Normal) (G1 Evacuation Pause) 424M->177M(512M) 6.242ms
|
||||||
|
[0.541s][info][gc] GC(9) Pause Young (Normal) (G1 Evacuation Pause) 438M->177M(512M) 8.665ms
|
||||||
|
[0.591s][info][gc] GC(10) Pause Young (Normal) (G1 Evacuation Pause) 447M->177M(512M) 8.525ms
|
||||||
|
[0.642s][info][gc] GC(11) Pause Young (Normal) (G1 Evacuation Pause) 455M->178M(512M) 7.669ms
|
||||||
|
[0.694s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 462M->178M(512M) 7.269ms
|
||||||
|
[0.748s][info][gc] GC(13) Pause Young (Normal) (G1 Evacuation Pause) 467M->178M(512M) 8.543ms
|
||||||
|
[0.801s][info][gc] GC(14) Pause Young (Normal) (G1 Evacuation Pause) 471M->178M(512M) 6.383ms
|
||||||
|
[0.857s][info][gc] GC(15) Pause Young (Normal) (G1 Evacuation Pause) 471M->179M(512M) 5.703ms
|
||||||
|
[0.910s][info][gc] GC(16) Pause Young (Normal) (G1 Evacuation Pause) 472M->179M(512M) 5.622ms
|
||||||
|
[0.962s][info][gc] GC(17) Pause Young (Normal) (G1 Evacuation Pause) 471M->179M(512M) 5.201ms
|
||||||
|
[1.014s][info][gc] GC(18) Pause Young (Normal) (G1 Evacuation Pause) 471M->180M(512M) 5.320ms
|
||||||
|
[1.065s][info][gc] GC(19) Pause Young (Normal) (G1 Evacuation Pause) 472M->180M(512M) 5.347ms
|
||||||
|
[1.117s][info][gc] GC(20) Pause Young (Normal) (G1 Evacuation Pause) 472M->180M(512M) 5.279ms
|
||||||
|
[1.168s][info][gc] GC(21) Pause Young (Normal) (G1 Evacuation Pause) 472M->180M(512M) 4.655ms
|
||||||
|
[1.217s][info][gc] GC(22) Pause Young (Normal) (G1 Evacuation Pause) 472M->180M(512M) 3.155ms
|
||||||
|
|
||||||
|
# the same run, counting what G1 did
|
||||||
|
88 Pause Young (Normal) (G1 Evacuation Pause)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Same workload, five collectors, JDK 25, -Xms1g -Xmx1g, 450 MB live set of small linked objects that are constantly replaced, 8 s measured after a 1.5 s warm-up, three runs each
|
||||||
|
# (2 vCPU sandbox: shape, not result. 'requests' counts completed loop iterations, a rough throughput signal)
|
||||||
|
|
||||||
|
## -XX:+UseSerialGC
|
||||||
|
run 1 requests : 2077033 (10135 MB allocated)
|
||||||
|
run 1 ticker max stall: 576.0 ms; wakeups >10 ms: 38; >50 ms: 26
|
||||||
|
run 2 requests : 2026832 (9889 MB allocated)
|
||||||
|
run 2 ticker max stall: 595.4 ms; wakeups >10 ms: 37; >50 ms: 24
|
||||||
|
run 3 requests : 1942997 (9479 MB allocated)
|
||||||
|
run 3 ticker max stall: 586.2 ms; wakeups >10 ms: 37; >50 ms: 17
|
||||||
|
|
||||||
|
## -XX:+UseParallelGC
|
||||||
|
run 1 requests : 957464 (4672 MB allocated)
|
||||||
|
run 1 ticker max stall: 538.7 ms; wakeups >10 ms: 19; >50 ms: 19
|
||||||
|
run 2 requests : 906922 (4425 MB allocated)
|
||||||
|
run 2 ticker max stall: 553.8 ms; wakeups >10 ms: 18; >50 ms: 18
|
||||||
|
run 3 requests : 908001 (4429 MB allocated)
|
||||||
|
run 3 ticker max stall: 536.8 ms; wakeups >10 ms: 18; >50 ms: 18
|
||||||
|
|
||||||
|
## -XX:+UseG1GC
|
||||||
|
run 1 requests : 3227925 (15750 MB allocated)
|
||||||
|
run 1 ticker max stall: 566.5 ms; wakeups >10 ms: 40; >50 ms: 35
|
||||||
|
run 2 requests : 3255959 (15885 MB allocated)
|
||||||
|
run 2 ticker max stall: 575.7 ms; wakeups >10 ms: 40; >50 ms: 40
|
||||||
|
run 3 requests : 3132846 (15284 MB allocated)
|
||||||
|
run 3 ticker max stall: 515.3 ms; wakeups >10 ms: 38; >50 ms: 35
|
||||||
|
|
||||||
|
## -XX:+UseZGC
|
||||||
|
run 1 requests : 5195766 (25350 MB allocated)
|
||||||
|
run 1 ticker max stall: 12.4 ms; wakeups >10 ms: 1; >50 ms: 0
|
||||||
|
run 2 requests : 5701049 (27813 MB allocated)
|
||||||
|
run 2 ticker max stall: 8.3 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
run 3 requests : 5588330 (27264 MB allocated)
|
||||||
|
run 3 ticker max stall: 13.0 ms; wakeups >10 ms: 1; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
|
||||||
|
run 1 requests : 1742398 (8501 MB allocated)
|
||||||
|
run 1 ticker max stall: 11.1 ms; wakeups >10 ms: 1; >50 ms: 0
|
||||||
|
run 2 requests : 1680239 (8197 MB allocated)
|
||||||
|
run 2 ticker max stall: 11.2 ms; wakeups >10 ms: 2; >50 ms: 0
|
||||||
|
run 3 requests : 1684136 (8216 MB allocated)
|
||||||
|
run 3 ticker max stall: 5.0 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# The defaults on each release, same workload and heap as 07, two runs each
|
||||||
|
|
||||||
|
## JDK 25: OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS), no collector flag
|
||||||
|
run 1 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 1 requests : 3243911 (15827 MB allocated)
|
||||||
|
run 1 ticker max stall: 78.1 ms; wakeups >10 ms: 37; >50 ms: 37
|
||||||
|
run 2 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 2 requests : 3279760 (16002 MB allocated)
|
||||||
|
run 2 ticker max stall: 534.3 ms; wakeups >10 ms: 39; >50 ms: 36
|
||||||
|
|
||||||
|
## JDK 27: OpenJDK Runtime Environment Temurin-27.0.1.1+4 (build 27.0.1.1+4), no collector flag
|
||||||
|
run 1 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 1 requests : 4914119 (23976 MB allocated)
|
||||||
|
run 1 ticker max stall: 600.6 ms; wakeups >10 ms: 53; >50 ms: 51
|
||||||
|
run 2 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 2 requests : 4690805 (22886 MB allocated)
|
||||||
|
run 2 ticker max stall: 512.3 ms; wakeups >10 ms: 53; >50 ms: 49
|
||||||
|
|
||||||
|
## JDK 28: OpenJDK Runtime Environment Temurin-28+25-202611191755 (build 28-beta+25-ea), no collector flag
|
||||||
|
run 1 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 1 requests : 4456120 (21741 MB allocated)
|
||||||
|
run 1 ticker max stall: 567.4 ms; wakeups >10 ms: 51; >50 ms: 49
|
||||||
|
run 2 collector beans : G1 Young Generation G1 Concurrent GC G1 Old Generation
|
||||||
|
run 2 requests : 4790262 (23369 MB allocated)
|
||||||
|
run 2 ticker max stall: 503.2 ms; wakeups >10 ms: 52; >50 ms: 49
|
||||||
|
|
||||||
|
## JDK 28 early access, -XX:+UseShenandoahGC with no mode flag
|
||||||
|
run 1 collector beans : Shenandoah Pauses Shenandoah Cycles
|
||||||
|
run 1 requests : 1758008 (8578 MB allocated)
|
||||||
|
run 1 ticker max stall: 301.2 ms; wakeups >10 ms: 29; >50 ms: 25
|
||||||
|
run 2 collector beans : Shenandoah Pauses Shenandoah Cycles
|
||||||
|
run 2 requests : 1760812 (8592 MB allocated)
|
||||||
|
run 2 ticker max stall: 289.3 ms; wakeups >10 ms: 27; >50 ms: 22
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# jcmd GC.heap_info on a live process, per collector (JDK 25, 512 MB heap, 150 MB live)
|
||||||
|
|
||||||
|
## -XX:+UseParallelGC
|
||||||
|
PSYoungGen total 163328K, used 67168K [0x00000000f5580000, 0x0000000100000000, 0x0000000100000000)
|
||||||
|
eden space 152064K, 37% used [0x00000000f5580000,0x00000000f8c783c8,0x00000000fea00000)
|
||||||
|
from space 11264K, 96% used [0x00000000ff500000,0x00000000fffa0000,0x0000000100000000)
|
||||||
|
to space 11264K, 0% used [0x00000000fea00000,0x00000000fea00000,0x00000000ff500000)
|
||||||
|
ParOldGen total 349696K, used 216440K [0x00000000e0000000, 0x00000000f5580000, 0x00000000f5580000)
|
||||||
|
object space 349696K, 61% used [0x00000000e0000000,0x00000000ed35e2e0,0x00000000f5580000)
|
||||||
|
|
||||||
|
## -XX:+UseG1GC
|
||||||
|
garbage-first heap total reserved 524288K, committed 524288K, used 214460K [0x00000000e0000000, 0x0000000100000000)
|
||||||
|
region size 1024K, 24 young (24576K), 15 survivors (15360K)
|
||||||
|
|
||||||
|
## -XX:+UseZGC
|
||||||
|
ZHeap used 320M, capacity 512M, max capacity 512M
|
||||||
|
Cache 192M (23)
|
||||||
|
size classes 2M (12), 4M (7), 8M (2), 32M (1), 64M (1)
|
||||||
|
|
||||||
|
## -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
|
||||||
|
Shenandoah Heap
|
||||||
|
512M max, 512M soft max, 512M committed, 261M used
|
||||||
|
2048 x 256 K regions
|
||||||
|
Status: not cancelled
|
||||||
|
Reserved region:
|
||||||
|
- [0x00000000e0000000, 0x0000000100000000)
|
||||||
|
Collection set:
|
||||||
|
- map (vanilla): 0x0000000000004800
|
||||||
|
- map (biased): 0x0000000000001000
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Running out of memory: the message depends on how the collector fails (JDK 25, -Xmx64m)
|
||||||
|
|
||||||
|
## G1, 1 MB arrays
|
||||||
|
kept 31 arrays of 1 MB then: java.lang.OutOfMemoryError: Java heap space
|
||||||
|
|
||||||
|
## G1, tiny objects
|
||||||
|
kept 1215487 tiny objects then: java.lang.OutOfMemoryError: Java heap space
|
||||||
|
|
||||||
|
## Parallel, tiny objects
|
||||||
|
kept 1160801 tiny objects then: java.lang.OutOfMemoryError: Java heap space
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# What one System.gc() costs (JDK 25, G1, 150 MB live)
|
||||||
|
|
||||||
|
## default
|
||||||
|
[0.187s][info][gc] GC(7) Pause Full (System.gc()) 156M->154M(267M) 22.122ms
|
||||||
|
System.gc() #1 took 22.5 ms
|
||||||
|
[0.224s][info][gc] GC(8) Pause Full (System.gc()) 155M->154M(267M) 18.764ms
|
||||||
|
System.gc() #2 took 18.9 ms
|
||||||
|
[0.238s][info][gc] GC(9) Pause Full (System.gc()) 155M->154M(267M) 13.827ms
|
||||||
|
System.gc() #3 took 14.0 ms
|
||||||
|
live chunks still referenced: 153600
|
||||||
|
|
||||||
|
## -XX:+DisableExplicitGC
|
||||||
|
System.gc() #1 took 0.1 ms
|
||||||
|
System.gc() #2 took 0.0 ms
|
||||||
|
System.gc() #3 took 0.0 ms
|
||||||
|
live chunks still referenced: 153600
|
||||||
|
|
||||||
|
## -XX:+ExplicitGCInvokesConcurrent
|
||||||
|
[0.203s][info][gc] GC(7) Pause Young (Concurrent Start) (System.gc()) 168M->168M(267M) 8.496ms
|
||||||
|
System.gc() #1 took 34.4 ms
|
||||||
|
[0.261s][info][gc] GC(9) Pause Young (Concurrent Start) (System.gc()) 168M->169M(285M) 4.044ms
|
||||||
|
System.gc() #2 took 31.7 ms
|
||||||
|
[0.290s][info][gc] GC(11) Pause Young (Concurrent Start) (System.gc()) 169M->168M(287M) 0.919ms
|
||||||
|
System.gc() #3 took 22.5 ms
|
||||||
|
live chunks still referenced: 153600
|
||||||
|
|
||||||
|
## ZGC
|
||||||
|
System.gc() #1 took 47.5 ms
|
||||||
|
System.gc() #2 took 23.6 ms
|
||||||
|
System.gc() #3 took 19.2 ms
|
||||||
|
live chunks still referenced: 153600
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# finalize() today
|
||||||
|
|
||||||
|
## what javac says (JDK 25, -Xlint:deprecation)
|
||||||
|
src/Finalize.java:13: warning: [removal] finalize() in Object has been deprecated and marked for removal
|
||||||
|
protected void finalize() { // deliberately not suppressed: javac prints a removal warning
|
||||||
|
^
|
||||||
|
1 warning
|
||||||
|
|
||||||
|
## JDK 25, default
|
||||||
|
finalize() ran
|
||||||
|
main done
|
||||||
|
|
||||||
|
## JDK 25, --finalization=disabled
|
||||||
|
main done
|
||||||
|
|
||||||
|
## JDK 27, default
|
||||||
|
finalize() ran
|
||||||
|
main done
|
||||||
|
|
||||||
|
## JDK 27, --finalization=disabled
|
||||||
|
main done
|
||||||
|
|
||||||
|
## JDK 28, default
|
||||||
|
finalize() ran
|
||||||
|
main done
|
||||||
|
|
||||||
|
## JDK 28, --finalization=disabled
|
||||||
|
main done
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# the other two snippets in the article, run
|
||||||
|
10 Hello
|
||||||
|
read byte count: 5
|
||||||
|
stream closed deterministically at the end of the try block
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# The baseline: a FLAT live set (one list of 1 KB byte arrays, no pointers inside), JDK 25, -Xms512m -Xmx512m, 150 MB live, 8 s, one run each
|
||||||
|
|
||||||
|
## -XX:+UseSerialGC
|
||||||
|
requests : 10735539 (52378 MB allocated)
|
||||||
|
ticker max stall: 8.6 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseParallelGC
|
||||||
|
requests : 13025302 (63552 MB allocated)
|
||||||
|
ticker max stall: 5.0 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseG1GC
|
||||||
|
requests : 8873404 (43294 MB allocated)
|
||||||
|
ticker max stall: 7.2 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseZGC
|
||||||
|
requests : 13262536 (64709 MB allocated)
|
||||||
|
ticker max stall: 6.3 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
|
||||||
|
requests : 9827770 (47951 MB allocated)
|
||||||
|
ticker max stall: 5.3 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Why is G1's worst case so uneven? Pause types and the three longest pauses in three G1 runs of the graph workload (JDK 25, -Xms1g -Xmx1g, 450 MB live)
|
||||||
|
|
||||||
|
## run 1
|
||||||
|
pause counts by type:
|
||||||
|
38 Pause Young (Normal)
|
||||||
|
5 Pause Young (Mixed)
|
||||||
|
5 Pause Young (Concurrent Start)
|
||||||
|
4 Pause Young (Prepare Mixed)
|
||||||
|
1 Pause Full (G1 Compaction Pause)
|
||||||
|
three longest pauses:
|
||||||
|
GC(51) Pause Full (G1 Compaction Pause) 1024M->464M(1024M) 467.261ms
|
||||||
|
GC(2) Pause Young (Normal) (G1 Evacuation Pause) 409M->409M(1024M) 109.383ms
|
||||||
|
GC(49) Pause Young (Mixed) (G1 Evacuation Pause) (Evacuation Failure: Allocation) 971M->975M(1024M) 106.895ms
|
||||||
|
|
||||||
|
## run 2
|
||||||
|
pause counts by type:
|
||||||
|
38 Pause Young (Normal)
|
||||||
|
5 Pause Young (Mixed)
|
||||||
|
5 Pause Young (Concurrent Start)
|
||||||
|
4 Pause Young (Prepare Mixed)
|
||||||
|
1 Pause Full (G1 Compaction Pause)
|
||||||
|
three longest pauses:
|
||||||
|
GC(51) Pause Full (G1 Compaction Pause) 1023M->464M(1024M) 467.847ms
|
||||||
|
GC(49) Pause Young (Mixed) (G1 Evacuation Pause) (Evacuation Failure: Allocation) 970M->979M(1024M) 132.893ms
|
||||||
|
GC(2) Pause Young (Normal) (G1 Evacuation Pause) 410M->410M(1024M) 111.761ms
|
||||||
|
|
||||||
|
## run 3
|
||||||
|
pause counts by type:
|
||||||
|
37 Pause Young (Normal)
|
||||||
|
5 Pause Young (Mixed)
|
||||||
|
5 Pause Young (Concurrent Start)
|
||||||
|
4 Pause Young (Prepare Mixed)
|
||||||
|
1 Pause Full (G1 Compaction Pause)
|
||||||
|
three longest pauses:
|
||||||
|
GC(51) Pause Full (G1 Compaction Pause) 1024M->464M(1024M) 507.602ms
|
||||||
|
GC(49) Pause Young (Mixed) (G1 Evacuation Pause) (Evacuation Failure: Allocation) 971M->975M(1024M) 121.870ms
|
||||||
|
GC(2) Pause Young (Normal) (G1 Evacuation Pause) 409M->410M(1024M) 118.036ms
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Heap is not the whole process: Native Memory Tracking on a live JVM (JDK 25, G1, -Xmx512m, 150 MB live)
|
||||||
|
$ jcmd <pid> VM.native_memory summary (category totals only)
|
||||||
|
Total: reserved=1973775KB, committed=597955KB
|
||||||
|
Java Heap (reserved=524288KB, committed=524288KB)
|
||||||
|
Class (reserved=1048647KB, committed=199KB)
|
||||||
|
Thread (reserved=20545KB, committed=1053KB)
|
||||||
|
Code (reserved=247794KB, committed=7650KB)
|
||||||
|
GC (reserved=47599KB, committed=47599KB)
|
||||||
|
GCCardSet (reserved=9KB, committed=9KB)
|
||||||
|
Compiler (reserved=214KB, committed=214KB)
|
||||||
|
Internal (reserved=1297KB, committed=1297KB)
|
||||||
|
Symbol (reserved=1131KB, committed=1131KB)
|
||||||
|
Native Memory Tracking (reserved=180KB, committed=180KB)
|
||||||
|
Shared class space (reserved=16384KB, committed=13928KB, readonly=0KB)
|
||||||
|
Arena Chunk (reserved=1KB, committed=1KB)
|
||||||
|
Tracing (reserved=5KB, committed=5KB)
|
||||||
|
Module (reserved=40KB, committed=40KB)
|
||||||
|
Safepoint (reserved=8KB, committed=8KB)
|
||||||
|
Synchronization (reserved=66KB, committed=66KB)
|
||||||
|
Serviceability (reserved=17KB, committed=17KB)
|
||||||
|
Metaspace (reserved=65548KB, committed=268KB)
|
||||||
|
String Deduplication (reserved=1KB, committed=1KB)
|
||||||
|
Object Monitors (reserved=1KB, committed=1KB)
|
||||||
|
|
||||||
|
resident set size of the process, from /proc: 549.477 MB
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# A few defaults worth knowing (JDK 25)
|
||||||
|
$ java -Xmx1g -XX:+UseG1GC -XX:+PrintFlagsFinal -version | grep ...
|
||||||
|
uint ConcGCThreads = 1 {product} {ergonomic}
|
||||||
|
size_t G1HeapRegionSize = 1048576 {product} {ergonomic}
|
||||||
|
uint InitiatingHeapOccupancyPercent = 45 {product} {default}
|
||||||
|
uintx MaxGCPauseMillis = 200 {product} {default}
|
||||||
|
uint ParallelGCThreads = 2 {product} {default}
|
||||||
|
$ java -Xmx1g -XX:+UseSerialGC -XX:+PrintFlagsFinal -version | grep -E 'NewRatio|SurvivorRatio|MaxTenuringThreshold'
|
||||||
|
uint MaxTenuringThreshold = 15 {product} {default}
|
||||||
|
uintx NewRatio = 2 {product} {default}
|
||||||
|
uintx SurvivorRatio = 8 {product} {default}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Shenandoah by JDK and mode, same graph workload as 07 (-Xms1g -Xmx1g, 450 MB live), one run each
|
||||||
|
|
||||||
|
## JDK 25, -XX:ShenandoahGCMode=satb
|
||||||
|
requests : 539727 (2633 MB allocated)
|
||||||
|
ticker max stall: 11.3 ms; wakeups >10 ms: 2; >50 ms: 0
|
||||||
|
|
||||||
|
## JDK 25, -XX:ShenandoahGCMode=generational
|
||||||
|
requests : 1710722 (8347 MB allocated)
|
||||||
|
ticker max stall: 10.7 ms; wakeups >10 ms: 1; >50 ms: 0
|
||||||
|
|
||||||
|
## JDK 27, -XX:ShenandoahGCMode=satb
|
||||||
|
requests : 652517 (3183 MB allocated)
|
||||||
|
ticker max stall: 1125.5 ms; wakeups >10 ms: 11; >50 ms: 11
|
||||||
|
|
||||||
|
## JDK 27, -XX:ShenandoahGCMode=generational
|
||||||
|
requests : 1075858 (5249 MB allocated)
|
||||||
|
ticker max stall: 1345.8 ms; wakeups >10 ms: 16; >50 ms: 16
|
||||||
|
|
||||||
|
## JDK 28, -XX:ShenandoahGCMode=satb
|
||||||
|
requests : 750947 (3663 MB allocated)
|
||||||
|
ticker max stall: 952.4 ms; wakeups >10 ms: 14; >50 ms: 14
|
||||||
|
|
||||||
|
## JDK 28, -XX:ShenandoahGCMode=generational
|
||||||
|
requests : 1854932 (9052 MB allocated)
|
||||||
|
ticker max stall: 307.9 ms; wakeups >10 ms: 27; >50 ms: 25
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Headroom: the graph workload again with a 2 GB heap instead of 1 GB (450 MB live is now 22 percent of the heap), JDK 25, one run each
|
||||||
|
|
||||||
|
## -XX:+UseSerialGC
|
||||||
|
requests : 4584936 (22369 MB allocated)
|
||||||
|
ticker max stall: 121.8 ms; wakeups >10 ms: 43; >50 ms: 43
|
||||||
|
|
||||||
|
## -XX:+UseParallelGC
|
||||||
|
requests : 6845614 (33401 MB allocated)
|
||||||
|
ticker max stall: 52.3 ms; wakeups >10 ms: 68; >50 ms: 1
|
||||||
|
|
||||||
|
## -XX:+UseG1GC
|
||||||
|
requests : 5148123 (25117 MB allocated)
|
||||||
|
ticker max stall: 132.1 ms; wakeups >10 ms: 23; >50 ms: 23
|
||||||
|
|
||||||
|
## -XX:+UseZGC
|
||||||
|
requests : 6501613 (31722 MB allocated)
|
||||||
|
ticker max stall: 8.1 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
|
||||||
|
requests : 2706531 (13206 MB allocated)
|
||||||
|
ticker max stall: 6.9 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# What Shenandoah did on each JDK for the graph workload (-Xms1g -Xmx1g, 450 MB live, generational mode, one run each): pause types and the three longest pauses
|
||||||
|
|
||||||
|
## JDK 25
|
||||||
|
pause counts by type:
|
||||||
|
42 Pause Final Mark
|
||||||
|
41 Pause Init Mark
|
||||||
|
38 Pause Init Update Refs
|
||||||
|
38 Pause Final Update Refs
|
||||||
|
three longest pauses:
|
||||||
|
GC(15) Pause Final Mark (Young) 5.844ms
|
||||||
|
GC(8) Pause Final Update Refs 1.035ms
|
||||||
|
GC(14) Pause Final Update Refs 0.412ms
|
||||||
|
|
||||||
|
## JDK 27
|
||||||
|
pause counts by type:
|
||||||
|
16 Pause Init Mark
|
||||||
|
15 Pause Degenerated GC
|
||||||
|
5 Pause Final Mark
|
||||||
|
3 Pause Full
|
||||||
|
three longest pauses:
|
||||||
|
GC(27) Pause Full 993M->434M(1024M) 1304.922ms
|
||||||
|
GC(18) Pause Full 993M->434M(1024M) 1210.941ms
|
||||||
|
GC(9) Pause Full 1024M->433M(1024M) 1152.424ms
|
||||||
|
|
||||||
|
## JDK 28
|
||||||
|
pause counts by type:
|
||||||
|
36 Pause Init Mark
|
||||||
|
35 Pause Final Mark
|
||||||
|
34 Pause Final Update Refs
|
||||||
|
three longest pauses:
|
||||||
|
GC(1) Pause Final Mark (Young) 0.321ms
|
||||||
|
GC(6) Pause Final Mark (Global) 0.265ms
|
||||||
|
GC(18) Pause Final Mark (Young) 0.232ms
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# A pause-free log is not a stall-free application: Shenandoah allocation stalls (generational mode, graph workload, -Xms1g -Xmx1g, 450 MB live, one run each)
|
||||||
|
|
||||||
|
## JDK 25
|
||||||
|
allocation stalls logged : 0
|
||||||
|
longest allocation stalls :
|
||||||
|
longest stop-the-world pause: 0.913ms
|
||||||
|
ticker max stall: 5.2 ms; wakeups >10 ms: 0; >50 ms: 0
|
||||||
|
|
||||||
|
## JDK 27
|
||||||
|
allocation stalls logged : 0
|
||||||
|
longest allocation stalls :
|
||||||
|
longest stop-the-world pause: 1293.419ms
|
||||||
|
ticker max stall: 1292.7 ms; wakeups >10 ms: 15; >50 ms: 15
|
||||||
|
|
||||||
|
## JDK 28
|
||||||
|
allocation stalls logged : 83
|
||||||
|
longest allocation stalls :
|
||||||
|
Allocation Stall (main) 285.067ms
|
||||||
|
Allocation Stall (main) 282.400ms
|
||||||
|
longest stop-the-world pause: 0.372ms
|
||||||
|
ticker max stall: 281.3 ms; wakeups >10 ms: 28; >50 ms: 22
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# The default collector inside real container limits (docker run --cpus --memory; needs Docker and the eclipse-temurin:25-jre and :27-jre images)
|
||||||
|
|
||||||
|
## eclipse-temurin:25-jre
|
||||||
|
--cpus=1 --memory=4g -> UseSerialGC
|
||||||
|
--cpus=2 --memory=1g -> UseSerialGC
|
||||||
|
--cpus=2 --memory=1500m -> UseSerialGC
|
||||||
|
--cpus=2 --memory=1791m -> UseSerialGC
|
||||||
|
--cpus=2 --memory=1792m -> UseG1GC
|
||||||
|
--cpus=2 --memory=1800m -> UseG1GC
|
||||||
|
--cpus=2 --memory=2g -> UseG1GC
|
||||||
|
|
||||||
|
## eclipse-temurin:27-jre
|
||||||
|
--cpus=1 --memory=4g -> UseG1GC
|
||||||
|
--cpus=2 --memory=1g -> UseG1GC
|
||||||
|
--cpus=2 --memory=1500m -> UseG1GC
|
||||||
|
--cpus=2 --memory=1791m -> UseG1GC
|
||||||
|
--cpus=2 --memory=1792m -> UseG1GC
|
||||||
|
--cpus=2 --memory=1800m -> UseG1GC
|
||||||
|
--cpus=2 --memory=2g -> UseG1GC
|
||||||
Executable
+126
@@ -0,0 +1,126 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file in output/. Needs JDK 25, 27 and a 28 early-access build on disk.
|
||||||
|
# JDK25=/path JDK27=/path JDK28=/path ./run.sh [step ...] (no step = all)
|
||||||
|
# Timings are machine dependent: read them as shape, not as results. Everything else is stable.
|
||||||
|
set -u
|
||||||
|
unset JAVA_TOOL_OPTIONS _JAVA_OPTIONS # sandbox proxy banner is noise in a transcript
|
||||||
|
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
JDK25="${JDK25:-/tmp/tools/j25}"; JDK27="${JDK27:-/tmp/tools/j27}"; JDK28="${JDK28:-/tmp/tools/j28}"
|
||||||
|
OUT="$HERE/output"; CLS="$HERE/target/classes"; mkdir -p "$OUT" "$CLS"
|
||||||
|
"$JDK25/bin/javac" -Xlint:deprecation -d "$CLS" "$HERE"/src/*.java 2>&1 | sed "s#$HERE/##" > "$OUT/00-javac-warnings.txt"
|
||||||
|
J() { local v=$1; shift; "$(eval echo \$JDK$v)/bin/java" "$@"; } # J 25 -cp ... Main
|
||||||
|
ver() { "$(eval echo \$JDK$1)/bin/java" -version 2>&1 | sed -n '2p'; }
|
||||||
|
say() { printf '\n## %s\n' "$*"; }
|
||||||
|
|
||||||
|
step_01() { { echo "# Which collector does the JVM pick when you name none? (emulating a 1, 2 and 4 CPU machine with -XX:ActiveProcessorCount)"
|
||||||
|
for v in 25 27 28; do say "JDK $v: $(ver $v)"
|
||||||
|
for p in 1 2 4; do echo "\$ java -XX:ActiveProcessorCount=$p Which"; J $v -XX:ActiveProcessorCount=$p -cp "$CLS" Which 2>&1 | grep -v 'processors seen\|max heap'; done
|
||||||
|
done; } > "$OUT/01-default-collector.txt"; }
|
||||||
|
|
||||||
|
step_02() { { echo "# The memory half of the rule cannot be emulated with -XX:MaxRAM on 27 or later"
|
||||||
|
for v in 25 27 28; do say "JDK $v"; echo "\$ java -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version | grep MaxRAM"; J $v -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version 2>&1 | grep -E ' MaxRAM |Ignoring option|Unrecognized VM|Could not create' | sed 's/ */ /g' | head -3; done; } > "$OUT/02-maxram.txt"; }
|
||||||
|
|
||||||
|
step_03() { { echo "# Shenandoah: which mode is the default, and is the generational mode still experimental? (mode read from -Xlog:gc+init)"
|
||||||
|
for v in 25 27 28; do say "JDK $v, no mode flag"; echo "\$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode"; J $v -XX:+UseShenandoahGC -Xlog:gc+init -version 2>&1 | grep -E 'Mode:|warning'; done
|
||||||
|
say "JDK 25: generational mode without -XX:+UnlockExperimentalVMOptions"; echo "\$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init -version"; J 25 -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init -version 2>&1 | grep -E 'Mode:|rror|warning|Unlock'
|
||||||
|
say "JDK 24-style spelling on 25 (the unlock flag is now unnecessary but harmless)"; J 25 -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init -version 2>&1 | grep -E 'Mode:|rror|warning'
|
||||||
|
say "JDK 28 early access: asking for the old mode explicitly"; echo "\$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xlog:gc+init -version"; J 28 -XX:+UseShenandoahGC -XX:ShenandoahGCMode=satb -Xlog:gc+init -version 2>&1 | grep -E 'Mode:|rror|warning|eprecat'; echo "(no deprecation warning is printed by this early-access build)"
|
||||||
|
} > "$OUT/03-shenandoah-modes.txt"; }
|
||||||
|
|
||||||
|
step_04() { { echo "# ZGC: the non-generational mode is gone, and what 28 adds"
|
||||||
|
say "JDK 25: ask for the old mode"; echo "\$ java -XX:+UseZGC -XX:-ZGenerational -version"; J 25 -XX:+UseZGC -XX:-ZGenerational -version 2>&1 | head -2
|
||||||
|
say "JDK 25: plain ZGC"; J 25 -XX:+UseZGC -cp "$CLS" Which 2>&1 | grep -v 'processors\|max heap'
|
||||||
|
say "ZGC flags present on 28 early access but not on 27 (diff of -XX:+PrintFlagsFinal -XX:+UseZGC, names only)"
|
||||||
|
J 27 -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -XX:+PrintFlagsFinal -version 2>/dev/null | awk '$2 ~ /^Z/ {print $2}' | sort > /tmp/z27.txt
|
||||||
|
J 28 -XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseZGC -XX:+PrintFlagsFinal -version 2>/dev/null | awk '$2 ~ /^Z/ {print $2}' | sort > /tmp/z28.txt
|
||||||
|
echo "only on 28:"; comm -13 /tmp/z27.txt /tmp/z28.txt; echo "only on 27:"; comm -23 /tmp/z27.txt /tmp/z28.txt
|
||||||
|
say "its default on 28"; J 28 -XX:+UseZGC -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E 'ZAdaptiveHeapSizing|SoftMaxHeapSize' | sed 's/ */ /g'
|
||||||
|
} > "$OUT/04-zgc.txt"; }
|
||||||
|
|
||||||
|
step_05() { { echo "# Reachability observed with weak references (JDK 25)"; J 25 -cp "$CLS" Reach; } > "$OUT/05-reachability.txt"; }
|
||||||
|
|
||||||
|
step_06() { { echo "# Reading a G1 log: the first lines of -Xlog:gc for the Churn workload (JDK 25, -Xms512m -Xmx512m, 150 MB live)"
|
||||||
|
echo "\$ java -Xms512m -Xmx512m -Xlog:gc Churn 150 3"; J 25 -Xms512m -Xmx512m -Xlog:gc -cp "$CLS" Churn 150 3 | grep -E '^\[' | head -24
|
||||||
|
echo; echo "# the same run, counting what G1 did"; J 25 -Xms512m -Xmx512m -Xlog:gc -cp "$CLS" Churn 150 3 | grep ' Pause ' | sed -E 's/^\[[^]]*\]\[[^]]*\]\[[^]]*\] GC\([0-9]+\) //; s/[0-9]+M->[0-9]+M\([0-9]+M\)//; s/[0-9.]+ms//' | sed 's/ *$//' | sort | uniq -c | sort -rn
|
||||||
|
} > "$OUT/06-g1-log.txt"; }
|
||||||
|
|
||||||
|
step_07() { { echo "# Same workload, five collectors, JDK 25, -Xms1g -Xmx1g, 450 MB live set of small linked objects that are constantly replaced, 8 s measured after a 1.5 s warm-up, three runs each"
|
||||||
|
echo "# (2 vCPU sandbox: shape, not result. 'requests' counts completed loop iterations, a rough throughput signal)"
|
||||||
|
for gc in "-XX:+UseSerialGC" "-XX:+UseParallelGC" "-XX:+UseG1GC" "-XX:+UseZGC" "-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational"; do
|
||||||
|
say "$gc"; for r in 1 2 3; do J 25 -Xms1g -Xmx1g $gc -cp "$CLS" Churn 450 8 graph | grep -E 'requests|ticker'| sed 's/^/ run '$r' /' ; done; done; } > "$OUT/07-five-collectors.txt"; }
|
||||||
|
|
||||||
|
step_08() { { echo "# The defaults on each release, same workload and heap as 07, two runs each"
|
||||||
|
for v in 25 27 28; do say "JDK $v: $(ver $v), no collector flag"; for r in 1 2; do J $v -Xms1g -Xmx1g -cp "$CLS" Churn 450 8 graph | grep -E 'collector|requests|ticker' | sed 's/^/ run '$r' /'; done; done
|
||||||
|
say "JDK 28 early access, -XX:+UseShenandoahGC with no mode flag"; for r in 1 2; do J 28 -Xms1g -Xmx1g -XX:+UseShenandoahGC -cp "$CLS" Churn 450 8 graph | grep -E 'collector|requests|ticker' | sed 's/^/ run '$r' /'; done; } > "$OUT/08-defaults-by-release.txt"; }
|
||||||
|
|
||||||
|
step_09() { { echo "# jcmd GC.heap_info on a live process, per collector (JDK 25, 512 MB heap, 150 MB live)"
|
||||||
|
for gc in "-XX:+UseParallelGC" "-XX:+UseG1GC" "-XX:+UseZGC" "-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational"; do
|
||||||
|
say "$gc"; rm -f /tmp/churn.out; ( exec "$JDK25/bin/java" -Xms512m -Xmx512m $gc -cp "$CLS" Churn 150 3 flat wait > /tmp/churn.out 2>&1 ) &
|
||||||
|
pid=$!; for i in $(seq 1 60); do grep -q READY /tmp/churn.out 2>/dev/null && break; sleep 0.5; done
|
||||||
|
"$JDK25/bin/jcmd" $pid GC.heap_info 2>&1 | grep -v "^$pid" ; wait $pid; done; } > "$OUT/09-heap-info.txt"; }
|
||||||
|
|
||||||
|
step_10() { { echo "# Running out of memory: the message depends on how the collector fails (JDK 25, -Xmx64m)"
|
||||||
|
say "G1, 1 MB arrays"; J 25 -Xmx64m -cp "$CLS" Leak big 2>&1 | tail -2
|
||||||
|
say "G1, tiny objects"; J 25 -Xmx64m -cp "$CLS" Leak small 2>&1 | tail -3
|
||||||
|
say "Parallel, tiny objects"; J 25 -Xmx64m -XX:+UseParallelGC -cp "$CLS" Leak small 2>&1 | tail -3
|
||||||
|
} > "$OUT/10-out-of-memory.txt"; }
|
||||||
|
|
||||||
|
step_11() { { echo "# What one System.gc() costs (JDK 25, G1, 150 MB live)"
|
||||||
|
say "default"; J 25 -Xlog:gc -cp "$CLS" SysGc | grep -E 'Pause Full|System.gc|live chunks'
|
||||||
|
say "-XX:+DisableExplicitGC"; J 25 -XX:+DisableExplicitGC -Xlog:gc -cp "$CLS" SysGc | grep -E 'System.gc|live chunks'
|
||||||
|
say "-XX:+ExplicitGCInvokesConcurrent"; J 25 -XX:+ExplicitGCInvokesConcurrent -Xlog:gc -cp "$CLS" SysGc | grep -E '\(System.gc\(\)\)|System.gc\(\) #|live chunks'
|
||||||
|
say "ZGC"; J 25 -XX:+UseZGC -cp "$CLS" SysGc
|
||||||
|
} > "$OUT/11-system-gc.txt"; }
|
||||||
|
|
||||||
|
step_12() { { echo "# finalize() today"
|
||||||
|
say "what javac says (JDK 25, -Xlint:deprecation)"; cat "$OUT/00-javac-warnings.txt"
|
||||||
|
for v in 25 27 28; do say "JDK $v, default"; J $v -cp "$CLS" 'Finalize' 2>&1 | head -3; say "JDK $v, --finalization=disabled"; J $v --finalization=disabled -cp "$CLS" Finalize 2>&1 | head -3; done; } > "$OUT/12-finalize.txt"; }
|
||||||
|
|
||||||
|
step_14() { { echo "# The baseline: a FLAT live set (one list of 1 KB byte arrays, no pointers inside), JDK 25, -Xms512m -Xmx512m, 150 MB live, 8 s, one run each"
|
||||||
|
for gc in "-XX:+UseSerialGC" "-XX:+UseParallelGC" "-XX:+UseG1GC" "-XX:+UseZGC" "-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational"; do
|
||||||
|
say "$gc"; J 25 -Xms512m -Xmx512m $gc -cp "$CLS" Churn 150 8 flat | grep -E 'requests|ticker' | sed 's/^/ /'; done; } > "$OUT/14-flat-live-set-baseline.txt"; }
|
||||||
|
|
||||||
|
step_15() { { echo "# Why is G1's worst case so uneven? Pause types and the three longest pauses in three G1 runs of the graph workload (JDK 25, -Xms1g -Xmx1g, 450 MB live)"
|
||||||
|
for r in 1 2 3; do say "run $r"; J 25 -Xms1g -Xmx1g -Xlog:gc -cp "$CLS" Churn 450 8 graph > /tmp/g1.log
|
||||||
|
echo "pause counts by type:"; grep -o 'Pause [A-Za-z]* ([^)]*)' /tmp/g1.log | sort | uniq -c | sort -rn
|
||||||
|
echo "three longest pauses:"; grep ' Pause ' /tmp/g1.log | awk '{print $NF "\t" $0}' | sort -rn | head -3 | cut -f2- | sed -E 's/^\[[^]]*\]\[[^]]*\]\[[^]]*\] //'; done; } > "$OUT/15-g1-pause-types.txt"; }
|
||||||
|
|
||||||
|
step_16() { { echo "# Heap is not the whole process: Native Memory Tracking on a live JVM (JDK 25, G1, -Xmx512m, 150 MB live)"
|
||||||
|
rm -f /tmp/churn.out; ( exec "$JDK25/bin/java" -Xms512m -Xmx512m -XX:NativeMemoryTracking=summary -cp "$CLS" Churn 150 3 flat wait > /tmp/churn.out 2>&1 ) &
|
||||||
|
pid=$!; for i in $(seq 1 60); do grep -q READY /tmp/churn.out 2>/dev/null && break; sleep 0.5; done
|
||||||
|
echo "\$ jcmd <pid> VM.native_memory summary (category totals only)"; "$JDK25/bin/jcmd" $pid VM.native_memory summary 2>&1 | grep -E '^-|^Total' | sed -E 's/^- +//' | cut -c1-110
|
||||||
|
echo; echo "resident set size of the process, from /proc: $(awk '/VmRSS/{print $2/1024 " MB"}' /proc/$pid/status)"; wait $pid; } > "$OUT/16-native-memory.txt"; }
|
||||||
|
|
||||||
|
step_17() { { echo "# A few defaults worth knowing (JDK 25)"
|
||||||
|
echo "\$ java -Xmx1g -XX:+UseG1GC -XX:+PrintFlagsFinal -version | grep ..."; J 25 -Xmx1g -XX:+UseG1GC -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' MaxGCPauseMillis | G1HeapRegionSize | InitiatingHeapOccupancyPercent | ParallelGCThreads | ConcGCThreads ' | sed 's/ */ /g'
|
||||||
|
echo "\$ java -Xmx1g -XX:+UseSerialGC -XX:+PrintFlagsFinal -version | grep -E 'NewRatio|SurvivorRatio|MaxTenuringThreshold'"; J 25 -Xmx1g -XX:+UseSerialGC -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' NewRatio | SurvivorRatio | MaxTenuringThreshold ' | sed 's/ */ /g'; } > "$OUT/17-flag-defaults.txt"; }
|
||||||
|
|
||||||
|
step_18() { { echo "# Shenandoah by JDK and mode, same graph workload as 07 (-Xms1g -Xmx1g, 450 MB live), one run each"
|
||||||
|
for v in 25 27 28; do for m in satb generational; do say "JDK $v, -XX:ShenandoahGCMode=$m"; J $v -Xms1g -Xmx1g -XX:+UseShenandoahGC -XX:ShenandoahGCMode=$m -cp "$CLS" Churn 450 8 graph | grep -E 'requests|ticker' | sed 's/^/ /'; done; done; } > "$OUT/18-shenandoah-by-jdk.txt"; }
|
||||||
|
|
||||||
|
step_19() { { echo "# Headroom: the graph workload again with a 2 GB heap instead of 1 GB (450 MB live is now 22 percent of the heap), JDK 25, one run each"
|
||||||
|
for gc in "-XX:+UseSerialGC" "-XX:+UseParallelGC" "-XX:+UseG1GC" "-XX:+UseZGC" "-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational"; do
|
||||||
|
say "$gc"; J 25 -Xms2g -Xmx2g $gc -cp "$CLS" Churn 450 8 graph | grep -E 'requests|ticker' | sed 's/^/ /'; done; } > "$OUT/19-headroom-2g.txt"; }
|
||||||
|
|
||||||
|
step_20() { { echo "# What Shenandoah did on each JDK for the graph workload (-Xms1g -Xmx1g, 450 MB live, generational mode, one run each): pause types and the three longest pauses"
|
||||||
|
for v in 25 27 28; do say "JDK $v"; J $v -Xms1g -Xmx1g -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc -cp "$CLS" Churn 450 8 graph > /tmp/sh.log
|
||||||
|
echo "pause counts by type:"; grep ' Pause ' /tmp/sh.log | grep -oE 'Pause (Init Mark|Final Mark|Degenerated GC|Full|Init Update Refs|Final Update Refs)' | sort | uniq -c | sort -rn
|
||||||
|
echo "three longest pauses:"; grep ' Pause ' /tmp/sh.log | awk '{print $NF "\t" $0}' | sort -rn | head -3 | cut -f2- | sed -E 's/^\[[^]]*\]\[[^]]*\]\[[^]]*\] //'; done; } > "$OUT/20-shenandoah-pause-types.txt"; }
|
||||||
|
|
||||||
|
step_21() { { echo "# A pause-free log is not a stall-free application: Shenandoah allocation stalls (generational mode, graph workload, -Xms1g -Xmx1g, 450 MB live, one run each)"
|
||||||
|
for v in 25 27 28; do say "JDK $v"; J $v -Xms1g -Xmx1g -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc -cp "$CLS" Churn 450 8 graph > /tmp/sh.log
|
||||||
|
echo "allocation stalls logged : $(grep -c 'Allocation Stall' /tmp/sh.log)"
|
||||||
|
echo "longest allocation stalls :"; grep 'Allocation Stall' /tmp/sh.log | awk '{print $NF "\t" $0}' | sort -rn | head -2 | cut -f2- | sed -E 's/^\[[^]]*\]\[[^]]*\]\[[^]]*\] //; s/^/ /'
|
||||||
|
echo "longest stop-the-world pause: $(grep ' Pause ' /tmp/sh.log | awk '{print $NF}' | sort -rn | head -1)"; grep ticker /tmp/sh.log; done; } > "$OUT/21-shenandoah-allocation-stalls.txt"; }
|
||||||
|
|
||||||
|
step_22() { { echo "# The default collector inside real container limits (docker run --cpus --memory; needs Docker and the eclipse-temurin:25-jre and :27-jre images)"
|
||||||
|
for img in 25 27; do say "eclipse-temurin:$img-jre"
|
||||||
|
for lim in "--cpus=1 --memory=4g" "--cpus=2 --memory=1g" "--cpus=2 --memory=1500m" "--cpus=2 --memory=1791m" "--cpus=2 --memory=1792m" "--cpus=2 --memory=1800m" "--cpus=2 --memory=2g"; do
|
||||||
|
printf '%-28s -> ' "$lim"; docker run --rm $lim eclipse-temurin:$img-jre java -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' Use(G1|Serial)GC ' | awk '$4=="true"{printf "%s", $2}'; echo
|
||||||
|
done; done; } > "$OUT/22-container-default-collector.txt"; }
|
||||||
|
|
||||||
|
step_13() { { echo "# the other two snippets in the article, run"; "$JDK25/bin/java" -cp "$CLS" StackAndHeap; "$JDK25/bin/java" -cp "$CLS" TryWithResources; } > "$OUT/13-small-demos.txt"; }
|
||||||
|
|
||||||
|
if [ $# -eq 0 ]; then set -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22; fi
|
||||||
|
for s in "$@"; do echo "step $s"; "step_$s"; done
|
||||||
|
echo "versions: $(ver 25) | $(ver 27) | $(ver 28)" > "$OUT/00-versions.txt"
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import java.lang.management.GarbageCollectorMXBean;
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A synthetic service: a live set that stays in memory plus a steady stream of short-lived garbage.
|
||||||
|
* A "ticker" thread asks to sleep 1 ms in a loop and records how late it wakes up; a stop-the-world pause shows up as lateness.
|
||||||
|
* Usage: Churn <liveMB> <seconds> [flat|graph] [wait]
|
||||||
|
* flat (default): the live set is one big list of 1 KB byte arrays: cheap for a collector to copy, no pointers inside.
|
||||||
|
* graph: the live set is a HashMap of small entries that are replaced all the time: many objects, many old-to-young pointers.
|
||||||
|
* wait: parks the JVM at the end so jcmd can look at it.
|
||||||
|
*/
|
||||||
|
public class Churn {
|
||||||
|
static volatile boolean stop;
|
||||||
|
static long maxStallNs, over10ms, over50ms;
|
||||||
|
|
||||||
|
static final List<byte[]> live = new ArrayList<>();
|
||||||
|
static final java.util.HashMap<Integer, byte[]> graph = new java.util.HashMap<>(); // "graph" mode: many small linked objects, mutated often
|
||||||
|
static boolean graphMode;
|
||||||
|
static int graphKeys;
|
||||||
|
static final byte[][] ring = new byte[16384][]; // recent "requests" stay reachable briefly, so the JIT cannot optimise the allocations away
|
||||||
|
static int slot;
|
||||||
|
static long allocatedBytes, ops;
|
||||||
|
|
||||||
|
/** Runs the request loop for the given time. */
|
||||||
|
static void serve(long nanos) {
|
||||||
|
var rnd = ThreadLocalRandom.current();
|
||||||
|
long end = System.nanoTime() + nanos;
|
||||||
|
allocatedBytes = 0;
|
||||||
|
ops = 0;
|
||||||
|
while (System.nanoTime() < end) {
|
||||||
|
// short-lived garbage: a few small arrays per "request"
|
||||||
|
for (int k = 0; k < 8; k++) {
|
||||||
|
byte[] b = new byte[256 + rnd.nextInt(768)];
|
||||||
|
ring[slot] = b;
|
||||||
|
slot = (slot + 1) & (ring.length - 1);
|
||||||
|
allocatedBytes += b.length;
|
||||||
|
}
|
||||||
|
// some requests replace one piece of the live set, so some objects live a while and then die
|
||||||
|
if (graphMode) { if ((ops & 1) == 0) graph.put(rnd.nextInt(graphKeys), new byte[48]); }
|
||||||
|
else if (ops % 200 == 0) live.set(rnd.nextInt(live.size()), new byte[1024]);
|
||||||
|
ops++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
int liveMb = Integer.parseInt(args[0]);
|
||||||
|
int seconds = Integer.parseInt(args[1]);
|
||||||
|
graphMode = args.length > 2 && args[2].equals("graph");
|
||||||
|
boolean waitForJcmd = args.length > 3 && args[3].equals("wait");
|
||||||
|
|
||||||
|
if (graphMode) {
|
||||||
|
graphKeys = liveMb * 1024 * 1024 / 120; // roughly 120 bytes per entry: HashMap node + Integer key + 48-byte array
|
||||||
|
for (int i = 0; i < graphKeys; i++) graph.put(i, new byte[48]);
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < liveMb * 1024; i++) live.add(new byte[1024]); // the live set: 1 KB chunks reachable for the whole run
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warm-up: let the JIT compile the loop and let the collector move the freshly built live set out of the young
|
||||||
|
// generation. Only after that does the ticker start, so a one-off startup pause is not mistaken for steady state.
|
||||||
|
serve(1_500_000_000L);
|
||||||
|
|
||||||
|
Thread ticker = new Thread(() -> {
|
||||||
|
long prev = System.nanoTime();
|
||||||
|
while (!stop) {
|
||||||
|
try { Thread.sleep(1); } catch (InterruptedException e) { return; }
|
||||||
|
long now = System.nanoTime();
|
||||||
|
long late = now - prev - 1_000_000L;
|
||||||
|
if (late > maxStallNs) maxStallNs = late;
|
||||||
|
if (late > 10_000_000L) over10ms++;
|
||||||
|
if (late > 50_000_000L) over50ms++;
|
||||||
|
prev = now;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ticker.setDaemon(true);
|
||||||
|
ticker.start();
|
||||||
|
|
||||||
|
serve(seconds * 1_000_000_000L);
|
||||||
|
|
||||||
|
if (waitForJcmd) { System.out.println("READY"); System.out.flush(); Thread.sleep(4000); }
|
||||||
|
stop = true;
|
||||||
|
Thread.sleep(5);
|
||||||
|
|
||||||
|
StringBuilder names = new StringBuilder();
|
||||||
|
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) names.append(b.getName()).append(" ");
|
||||||
|
System.out.printf("collector beans : %s%n", names.toString().trim());
|
||||||
|
System.out.printf("live set : %d MB (%s), heap max %d MB%n", liveMb, graphMode ? "graph" : "flat", Runtime.getRuntime().maxMemory() >> 20);
|
||||||
|
System.out.printf("requests : %d (%.0f MB allocated)%n", ops, allocatedBytes / 1048576.0);
|
||||||
|
System.out.printf("ticker max stall: %.1f ms; wakeups >10 ms: %d; >50 ms: %d%n", maxStallNs / 1e6, over10ms, over50ms);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/** What finalize() does today. Compile with -Xlint:deprecation to see the compiler's view of it. */
|
||||||
|
public class Finalize {
|
||||||
|
static class Holder {
|
||||||
|
@SuppressWarnings({"removal", "deprecation"})
|
||||||
|
@Override
|
||||||
|
protected void finalize() {
|
||||||
|
System.out.println("finalize() ran");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Holder2 {
|
||||||
|
@Override
|
||||||
|
protected void finalize() { // deliberately not suppressed: javac prints a removal warning
|
||||||
|
System.out.println("finalize() ran");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
new Holder();
|
||||||
|
System.gc();
|
||||||
|
Thread.sleep(500);
|
||||||
|
System.out.println("main done");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** A classic leak: a static collection that only ever grows. Argument "big" keeps 1 MB arrays, "small" keeps tiny objects. */
|
||||||
|
public class Leak {
|
||||||
|
static final List<Object> CACHE = new ArrayList<>(); // a GC root: nothing ever removes from it
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
boolean big = args.length > 0 && args[0].equals("big");
|
||||||
|
long n = 0;
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
CACHE.add(big ? new byte[1 << 20] : new int[8]);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
} catch (OutOfMemoryError e) {
|
||||||
|
int kept = CACHE.size();
|
||||||
|
CACHE.clear(); // give the JVM room to print
|
||||||
|
System.out.println("kept " + kept + (big ? " arrays of 1 MB" : " tiny objects") + " then: java.lang.OutOfMemoryError: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import java.lang.ref.WeakReference;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reachability, observed. A WeakReference does not keep its target alive, so after a full collection
|
||||||
|
* "get() == null" means "the collector found it unreachable from the roots".
|
||||||
|
*/
|
||||||
|
public class Reach {
|
||||||
|
static class MyObject {
|
||||||
|
final String name;
|
||||||
|
MyObject child;
|
||||||
|
MyObject(String name) { this.name = name; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MyObject staticObj; // a GC root: a static field
|
||||||
|
|
||||||
|
static WeakReference<MyObject> weak(MyObject o) { return new WeakReference<>(o); }
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
MyObject localObj = new MyObject("A"); // a GC root: a local variable
|
||||||
|
staticObj = new MyObject("B");
|
||||||
|
localObj.child = new MyObject("C"); // 'C' is reachable from 'A'
|
||||||
|
MyObject unreachable = new MyObject("D"); // referenced by nothing once we drop the variable
|
||||||
|
|
||||||
|
// An "island": two objects that point at each other, with no path from any root.
|
||||||
|
MyObject x = new MyObject("X");
|
||||||
|
MyObject y = new MyObject("Y");
|
||||||
|
x.child = y;
|
||||||
|
y.child = x;
|
||||||
|
|
||||||
|
var refs = new WeakReference[] { weak(localObj), weak(staticObj), weak(localObj.child), weak(unreachable), weak(x), weak(y) };
|
||||||
|
String[] names = { "A (local variable)", "B (static field)", "C (child of A)", "D (no references)", "X (cycle with Y, no root)", "Y (cycle with X, no root)" };
|
||||||
|
|
||||||
|
unreachable = null;
|
||||||
|
x = null;
|
||||||
|
y = null;
|
||||||
|
|
||||||
|
System.gc(); // for the demonstration only; see "Forget System.gc() exists" in the article
|
||||||
|
|
||||||
|
for (int i = 0; i < refs.length; i++) {
|
||||||
|
System.out.printf("%-28s %s%n", names[i], refs[i].get() != null ? "alive" : "collected");
|
||||||
|
}
|
||||||
|
System.out.println("A and C are still used here: " + localObj.name + " -> " + localObj.child.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user