Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b7N4ZDbUtA3ofqAqRV
50 lines
2.4 KiB
Java
50 lines
2.4 KiB
Java
import java.time.Duration;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import jdk.jfr.Recording;
|
|
import jdk.jfr.consumer.RecordedEvent;
|
|
import jdk.jfr.consumer.RecordingFile;
|
|
import java.nio.file.Files;
|
|
|
|
/**
|
|
* What JEP 491 did NOT fix: blocking while a class is being initialized still pins the carrier.
|
|
* 8 virtual threads each initialize a different class whose static initializer sleeps 100 ms.
|
|
*/
|
|
public class ClassInitPinningProbe {
|
|
static class C0 { static { nap(); } static void touch() { } }
|
|
static class C1 { static { nap(); } static void touch() { } }
|
|
static class C2 { static { nap(); } static void touch() { } }
|
|
static class C3 { static { nap(); } static void touch() { } }
|
|
static class C4 { static { nap(); } static void touch() { } }
|
|
static class C5 { static { nap(); } static void touch() { } }
|
|
static class C6 { static { nap(); } static void touch() { } }
|
|
static class C7 { static { nap(); } static void touch() { } }
|
|
|
|
static void nap() {
|
|
try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); }
|
|
}
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
Runnable[] work = {C0::touch, C1::touch, C2::touch, C3::touch, C4::touch, C5::touch, C6::touch, C7::touch};
|
|
try (var rec = new Recording()) {
|
|
rec.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ofMillis(20));
|
|
rec.start();
|
|
long start = System.nanoTime();
|
|
List<Thread> threads = new ArrayList<>();
|
|
for (Runnable r : work) threads.add(Thread.ofVirtual().start(r));
|
|
for (Thread t : threads) t.join();
|
|
long ms = (System.nanoTime() - start) / 1_000_000;
|
|
rec.stop();
|
|
var file = Files.createTempFile("pin", ".jfr");
|
|
rec.dump(file);
|
|
List<RecordedEvent> events = RecordingFile.readAllEvents(file);
|
|
Files.delete(file);
|
|
System.out.println("java " + Runtime.version().feature() + ": 8 classes, 100 ms sleep inside each static initializer");
|
|
System.out.println("elapsed = " + ms + " ms, jdk.VirtualThreadPinned events = " + events.size());
|
|
if (!events.isEmpty() && events.get(0).hasField("pinnedReason")) {
|
|
System.out.println("first event pinnedReason = " + events.get(0).getString("pinnedReason"));
|
|
}
|
|
}
|
|
}
|
|
}
|