From 5127e0c99c68fa0fb9595309cc88d3f65154a26e Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:32:24 -0600 Subject: [PATCH 1/5] perf(vthread): pack the frames of a yielded continuation into one array --- src/natives/continuation.ts | 86 ++++++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 29 deletions(-) diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index ac12ffa..ebeca48 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -6,6 +6,7 @@ // virtual thread while it is not (JEP 491): a yield, a contended enter and // Object.wait all unmount it, and the monitors move to a stand-in owner. +import { JMethod } from "../runtime.ts"; import type { JObject, Monitor } from "../runtime.ts"; import { Frame, JThread, NativeFrame, PendingThrow, RUNNABLE, Signal, WAITING } from "../thread.ts"; import type { AnyFrame, NativeGen } from "../thread.ts"; @@ -27,40 +28,56 @@ type Entry = NonNullable; // Frame and its two arrays cost about 300 bytes, the packed values about 100. const PACK_AT = 1024; -// A frame as values: [method, pc, sp, lock, needLock, ...locals, ...stack up to sp]. +// Frames as values in one array, bottom first. A frame without a monitor is +// [method, pc, sp, ...locals, ...stack up to sp]; any other frame is itself. type Packed = any[]; -function pack(f: AnyFrame): AnyFrame | Packed { - if (!(f instanceof Frame) || f.direct || f.locals === null) return f; - const max = f.m.code!.maxLocals; - const p: Packed = new Array(5 + max + f.sp); - p[0] = f.m; - p[1] = f.pc; - p[2] = f.sp; - p[3] = f.lock; - p[4] = f.needLock; - for (let i = 0; i < max; i++) p[5 + i] = f.locals[i]; - for (let i = 0; i < f.sp; i++) p[5 + max + i] = f.stack[i]; +function packable(f: AnyFrame): f is Frame { + return f instanceof Frame && !f.direct && f.locals !== null && f.lock === null && !f.needLock; +} + +function pack(frames: AnyFrame[]): Packed { + let n = 0; + for (const f of frames) n += packable(f) ? 3 + f.locals.length + f.sp : 1; + const p: Packed = new Array(n); + let i = 0; + for (const f of frames) { + if (!packable(f)) { + p[i++] = f; + continue; + } + p[i++] = f.m; + p[i++] = f.pc; + p[i++] = f.sp; + for (let j = 0; j < f.locals.length; j++) p[i++] = f.locals[j]; + for (let j = 0; j < f.sp; j++) p[i++] = f.stack[j]; + } return p; } -function unpack(p: AnyFrame | Packed): AnyFrame { - if (!Array.isArray(p)) return p; - const f = new Frame(p[0]); - f.pc = p[1]; - f.sp = p[2]; - f.lock = p[3]; - f.needLock = p[4]; - const max = f.locals.length; - for (let i = 0; i < max; i++) f.locals[i] = p[5 + i]; - for (let i = 0; i < f.sp; i++) f.stack[i] = p[5 + max + i]; - return f; +function unpackInto(out: AnyFrame[], p: Packed) { + for (let i = 0; i < p.length; ) { + const x = p[i]; + if (!(x instanceof JMethod)) { + out.push(x); + i++; + continue; + } + const f = new Frame(x); + f.pc = p[i + 1]; + f.sp = p[i + 2]; + i += 3; + for (let j = 0; j < f.locals.length; j++) f.locals[j] = p[i++]; + for (let j = 0; j < f.sp; j++) f.stack[j] = p[i++]; + out.push(f); + } } // What a yielded continuation needs to resume, kept in its object's x. interface Frozen { - // its frames, bottom first - frames: (AnyFrame | Packed)[]; + // its frames, bottom first, or packed + frames: AnyFrame[] | Packed; + packed: boolean; // the top frame re-executes its instruction instead of taking a result retry: boolean; // monitors its virtual thread owns, and the owner standing in for it @@ -68,6 +85,8 @@ interface Frozen { owner: JThread | null; } +const NO_MONITORS: JObject[] = []; + interface State { // virtual threads whose monitor was released, for the unblocker thread unblock: JObject[]; @@ -86,7 +105,12 @@ function state(vm: JVM): State { // The continuation a native frame is the entry of, if it is one. // The frames of a yielded continuation, bottom first. export function frozenFrames(c: JObject): AnyFrame[] | undefined { - return (c.x as Frozen | undefined)?.frames.map(unpack); + const info = c.x as Frozen | undefined; + if (!info) return undefined; + if (!info.packed) return info.frames as AnyFrame[]; + const out: AnyFrame[] = []; + unpackInto(out, info.frames); + return out; } // Index in t.frames of the innermost mounted continuation's entry frame. @@ -127,7 +151,7 @@ export function dropOwned(t: JThread, o: JObject) { function freeze(t: JThread, e: number, count: number, retry: boolean) { const s = state(t.vm); const entry = (t.frames[e] as NativeFrame).entry!; - const info: Frozen = { frames: [], retry, monitors: [], owner: null }; + const info: Frozen = { frames: [], packed: false, retry, monitors: NO_MONITORS, owner: null }; if (entry.virtual) { const monitors = [...new Set(t.owned)].filter((o) => o.mon?.owner === t); t.owned = []; @@ -141,7 +165,10 @@ function freeze(t: JThread, e: number, count: number, retry: boolean) { } } const frames = t.frames.splice(e + 1, count); - info.frames = s.frozenCount >= PACK_AT ? frames.map(pack) : frames; + if (s.frozenCount >= PACK_AT) { + info.frames = pack(frames); + info.packed = true; + } else info.frames = frames; entry.cont.x = info; s.frozenCount++; s.busy = true; @@ -215,7 +242,8 @@ export const natives: Natives = { c.x = undefined; s.frozenCount--; setChunk(t, c, false); - for (const f of info.frames) t.frames.push(unpack(f)); + if (info.packed) unpackInto(t.frames, info.frames); + else for (const f of info.frames as AnyFrame[]) t.frames.push(f); if (info.owner) { for (const o of info.monitors) o.mon!.owner = t; t.owned = info.monitors; From 3fa412f89c0d910904b2db11cbb2625721931e1a Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:33:03 -0600 Subject: [PATCH 2/5] perf(vthread): share the two stack chunks between all continuations --- src/natives/continuation.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index ebeca48..7b5ae2f 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -94,11 +94,13 @@ interface State { active: number; frozenCount: number; busy: boolean; + // the chunk of a yielded continuation and of a mounted one + chunks: (JObject | undefined)[]; } function state(vm: JVM): State { let s = vm.state.get("continuations") as State | undefined; - if (!s) vm.state.set("continuations", (s = { unblock: [], unblocker: null, active: 0, frozenCount: 0, busy: false })); + if (!s) vm.state.set("continuations", (s = { unblock: [], unblocker: null, active: 0, frozenCount: 0, busy: false, chunks: [] })); return s; } @@ -211,16 +213,19 @@ export function unmountNative(t: JThread) { } // Continuation.tail: isStarted() and isEmpty() read it, so a yielded -// continuation has a chunk that is not empty, and a mounted one an empty chunk. +// continuation has a chunk that is not empty, and a mounted one an empty +// chunk. All continuations share the two chunks. function setChunk(t: JThread, c: JObject, frozen: boolean) { const vm = t.vm; - let chunk = vm.getField(c, C, "tail") as JObject | null; + const s = state(vm); + const i = frozen ? 0 : 1; + let chunk = s.chunks[i]; if (!chunk) { - chunk = vm.newObject(vm.loadBoot(CHUNK)!); - vm.setField(c, C, "tail", chunk); + chunk = s.chunks[i] = vm.newObject(vm.loadBoot(CHUNK)!); + vm.setField(chunk, CHUNK, "bottom", 1); + vm.setField(chunk, CHUNK, "sp", i); } - vm.setField(chunk, CHUNK, "bottom", 1); - vm.setField(chunk, CHUNK, "sp", frozen ? 0 : 1); + vm.setField(c, C, "tail", chunk); } export const natives: Natives = { From 302e8805fa7fb4bac248e0e2e5490c6e07025448 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:33:27 -0600 Subject: [PATCH 3/5] perf(monitor): allocate a monitor's entry and wait queues only while a thread uses them --- src/jvm.ts | 11 ++++++----- src/natives/continuation.ts | 2 +- src/natives/lang.ts | 14 ++++++-------- src/runtime.ts | 22 ++++++++++++++++++---- src/snapshot.ts | 6 +++--- 5 files changed, 34 insertions(+), 21 deletions(-) diff --git a/src/jvm.ts b/src/jvm.ts index 79a9673..37e2bcc 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -1005,7 +1005,7 @@ export class JVM { this.setThreadStatus(t, STATUS_BLOCKED); } t.state = WAITING; - o.mon!.entry.push(() => this.wake(t, true)); + o.mon!.enqueue(() => this.wake(t, true)); return false; } @@ -1044,8 +1044,8 @@ export class JVM { mon.owner = null; mon.count = 0; const entry = mon.entry; - if (entry.length === 0) return; - mon.entry = []; + if (entry === null) return; + mon.entry = null; for (const w of entry) w(); } @@ -1189,7 +1189,7 @@ export class JVM { // Thread.join waits on the thread object, checking isAlive() under its // monitor. Take the monitor first, as HotSpot's ensure_join does, so a // joiner between isAlive() and wait() cannot miss the wakeup. - while (!this.tryMonitorEnter(t, obj)) yield t.block(new Signal((r) => obj.mon!.entry.push(r))); + while (!this.tryMonitorEnter(t, obj)) yield t.block(new Signal((r) => obj.mon!.enqueue(r))); const holder = this.getField(obj, "java/lang/Thread", "holder") as JObject; this.setField(holder, "java/lang/Thread$FieldHolder", "threadStatus", STATUS_TERMINATED); this.setField(obj, "java/lang/Thread", "eetop", 0n); @@ -1201,7 +1201,8 @@ export class JVM { const mon = o.mon; if (!mon) return; const w = mon.waiters; - mon.waiters = []; + if (w === null) return; + mon.waiters = null; for (const x of w) x.wake(); } diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index 7b5ae2f..ccf3ac7 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -191,7 +191,7 @@ function queueUnblock(vm: JVM, vt: JObject) { // Queues vt for the unblocker thread when mon is released. export function unblockOnRelease(vm: JVM, vt: JObject, mon: Monitor) { - mon.entry.push(() => queueUnblock(vm, vt)); + mon.enqueue(() => queueUnblock(vm, vt)); } // A virtual thread that tried to take o's monitor and cannot: unmounts it, diff --git a/src/natives/lang.ts b/src/natives/lang.ts index 7819cc2..b65710b 100644 --- a/src/natives/lang.ts +++ b/src/natives/lang.ts @@ -72,12 +72,11 @@ function* waitImpl(t: JThread, self: JObject, ms: bigint): NativeGen { let entry: { t: JThread; wake: () => void; count: number } | null = null; yield t.block(interruptibleWait(t, ms > 0n ? Number(ms) : null, (wake) => { entry = { t, wake, count }; - mon.waiters.push(entry); + mon.addWaiter(entry); })); - const i = mon.waiters.indexOf(entry!); - if (i >= 0) mon.waiters.splice(i, 1); + mon.removeWaiter(entry!); if (mon.owner !== null) setThreadStatus(t, STATUS_BLOCKED); - while (mon.owner !== null) yield t.block(new Signal((r) => mon.entry.push(r))); + while (mon.owner !== null) yield t.block(new Signal((r) => mon.enqueue(r))); mon.owner = t; mon.count = count; t.waitingOn = null; @@ -109,10 +108,9 @@ function* waitUnmounted(t: JThread, self: JObject, mon: Monitor, ms: bigint): Na unblockOnRelease(vm, vt, mon); }; const waiter = { t, wake, count }; - mon.waiters.push(waiter); + mon.addWaiter(waiter); t = (yield { kind: "unmount" }) as JThread; - const i = mon.waiters.indexOf(waiter); - if (i >= 0) mon.waiters.splice(i, 1); + mon.removeWaiter(waiter); while (mon.owner !== null) { vm.setField(vt, VT, "state", VT_BLOCKING); unblockOnRelease(vm, vt, mon); @@ -220,7 +218,7 @@ export const natives: Natives = { "java/lang/Object.notify()V": (t, [o]) => { const mon = o.mon; if (!mon || mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); - mon.waiters.shift()?.wake(); + mon.waiters?.shift()?.wake(); }, "java/lang/Object.notifyAll()V": (t, [o]) => { if (!o.mon || o.mon.owner !== t) throw new PendingThrow("java/lang/IllegalMonitorStateException", "current thread is not owner"); diff --git a/src/runtime.ts b/src/runtime.ts index 346fbd3..aa66694 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -229,13 +229,27 @@ const EMPTY: any[] = []; export class Monitor { owner: JThread | null = null; count = 0; - // threads blocked entering the monitor - entry: (() => void)[] = []; - // threads in wait(), woken by notify + // threads blocked entering the monitor; the queues exist while they are used + entry: (() => void)[] | null = null; // threads in wait(), woken by notify, with the entry count they gave up - waiters: { t: JThread; wake: () => void; count: number }[] = []; + waiters: Waiter[] | null = null; + + enqueue(wake: () => void) { + (this.entry ??= []).push(wake); + } + + addWaiter(w: Waiter) { + (this.waiters ??= []).push(w); + } + + removeWaiter(w: Waiter) { + const i = this.waiters?.indexOf(w) ?? -1; + if (i >= 0) this.waiters!.splice(i, 1); + } } +export type Waiter = { t: JThread; wake: () => void; count: number }; + // Classes of the boot, platform and application loaders are never unloaded. const BUILTIN_LOADERS = new Set(["jdk/internal/loader/ClassLoaders$AppClassLoader", "jdk/internal/loader/ClassLoaders$PlatformClassLoader"]); export function dropsWithLoader(loader: JObject | null): boolean { diff --git a/src/snapshot.ts b/src/snapshot.ts index 8b6f05a..aebce49 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -248,7 +248,7 @@ class Encoder { if (k === undefined) throw new Error(`snapshot: unknown thread in ${path}`); t = { $: "T", i: k }; } else if (v instanceof Monitor) { - if (v.entry.length) throw new Error(`snapshot: a thread is blocked entering a monitor in ${path}`); + if (v.entry?.length) throw new Error(`snapshot: a thread is blocked entering a monitor in ${path}`); t = { $: "N", n: v.count }; this.work.push(() => (t.o = this.child(v.owner, path, next))); } else if (v instanceof Map) { @@ -464,7 +464,7 @@ export function dumpVM(vm: JVM, main: JThread, key: string, library = false): Sn if (key === REF_WAIT) return { $: "native", m: e.enc(f.m, p) }; if (key === WAIT0) { const o = (t.frames[i - 1] as Frame).locals[0] as JObject; - const w = o.mon?.waiters.find((x) => x.t === t); + const w = o.mon?.waiters?.find((x) => x.t === t); if (!w) throw new Error(`snapshot: ${p} in wait0 is not a waiter`); return { $: "rewait", m: e.enc(f.m, p), o: e.enc(o, p), n: w.count }; } @@ -501,7 +501,7 @@ function snapshotFds(value: unknown): unknown { function* rewait(t: JThread, o: JObject, count: number): NativeGen { const mon = o.mon!; t.waitingOn = o; - while (mon.owner !== null) yield t.block(new Signal((r) => mon.entry.push(r))); + while (mon.owner !== null) yield t.block(new Signal((r) => mon.enqueue(r))); mon.owner = t; mon.count = count; t.waitingOn = null; From 66ec26d5c80f44e5cc090417d95278c392ce0066 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:42:01 -0600 Subject: [PATCH 4/5] perf(vthread): store a packed frame's pc and sp in one value and fold the frozen flags into one --- src/natives/continuation.ts | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/natives/continuation.ts b/src/natives/continuation.ts index ccf3ac7..9d39aa8 100644 --- a/src/natives/continuation.ts +++ b/src/natives/continuation.ts @@ -29,7 +29,7 @@ type Entry = NonNullable; const PACK_AT = 1024; // Frames as values in one array, bottom first. A frame without a monitor is -// [method, pc, sp, ...locals, ...stack up to sp]; any other frame is itself. +// [method, pc + sp * 65536, ...locals, ...stack up to sp]; any other frame is itself. type Packed = any[]; function packable(f: AnyFrame): f is Frame { @@ -38,7 +38,7 @@ function packable(f: AnyFrame): f is Frame { function pack(frames: AnyFrame[]): Packed { let n = 0; - for (const f of frames) n += packable(f) ? 3 + f.locals.length + f.sp : 1; + for (const f of frames) n += packable(f) ? 2 + f.locals.length + f.sp : 1; const p: Packed = new Array(n); let i = 0; for (const f of frames) { @@ -47,8 +47,7 @@ function pack(frames: AnyFrame[]): Packed { continue; } p[i++] = f.m; - p[i++] = f.pc; - p[i++] = f.sp; + p[i++] = f.pc + f.sp * 65536; for (let j = 0; j < f.locals.length; j++) p[i++] = f.locals[j]; for (let j = 0; j < f.sp; j++) p[i++] = f.stack[j]; } @@ -64,9 +63,10 @@ function unpackInto(out: AnyFrame[], p: Packed) { continue; } const f = new Frame(x); - f.pc = p[i + 1]; - f.sp = p[i + 2]; - i += 3; + const at = p[i + 1]; + f.pc = at & 0xffff; + f.sp = at >>> 16; + i += 2; for (let j = 0; j < f.locals.length; j++) f.locals[j] = p[i++]; for (let j = 0; j < f.sp; j++) f.stack[j] = p[i++]; out.push(f); @@ -77,15 +77,16 @@ function unpackInto(out: AnyFrame[], p: Packed) { interface Frozen { // its frames, bottom first, or packed frames: AnyFrame[] | Packed; - packed: boolean; // the top frame re-executes its instruction instead of taking a result - retry: boolean; + flags: number; // monitors its virtual thread owns, and the owner standing in for it monitors: JObject[]; owner: JThread | null; } const NO_MONITORS: JObject[] = []; +// Frozen.flags +const RETRY = 1, PACKED = 2; interface State { // virtual threads whose monitor was released, for the unblocker thread @@ -109,7 +110,7 @@ function state(vm: JVM): State { export function frozenFrames(c: JObject): AnyFrame[] | undefined { const info = c.x as Frozen | undefined; if (!info) return undefined; - if (!info.packed) return info.frames as AnyFrame[]; + if (!(info.flags & PACKED)) return info.frames as AnyFrame[]; const out: AnyFrame[] = []; unpackInto(out, info.frames); return out; @@ -153,7 +154,7 @@ export function dropOwned(t: JThread, o: JObject) { function freeze(t: JThread, e: number, count: number, retry: boolean) { const s = state(t.vm); const entry = (t.frames[e] as NativeFrame).entry!; - const info: Frozen = { frames: [], packed: false, retry, monitors: NO_MONITORS, owner: null }; + const info: Frozen = { frames: [], flags: retry ? RETRY : 0, monitors: NO_MONITORS, owner: null }; if (entry.virtual) { const monitors = [...new Set(t.owned)].filter((o) => o.mon?.owner === t); t.owned = []; @@ -169,7 +170,7 @@ function freeze(t: JThread, e: number, count: number, retry: boolean) { const frames = t.frames.splice(e + 1, count); if (s.frozenCount >= PACK_AT) { info.frames = pack(frames); - info.packed = true; + info.flags |= PACKED; } else info.frames = frames; entry.cont.x = info; s.frozenCount++; @@ -247,7 +248,7 @@ export const natives: Natives = { c.x = undefined; s.frozenCount--; setChunk(t, c, false); - if (info.packed) unpackInto(t.frames, info.frames); + if (info.flags & PACKED) unpackInto(t.frames, info.frames); else for (const f of info.frames as AnyFrame[]) t.frames.push(f); if (info.owner) { for (const o of info.monitors) o.mon!.owner = t; @@ -256,7 +257,7 @@ export const natives: Natives = { const top = t.top; // a native resumes with the thread it now runs on; a frame that yielded gets the result if (top instanceof NativeFrame) top.input = t; - else if (!info.retry) { + else if (!(info.flags & RETRY)) { top.stack[top.sp++] = 0; top.pc += 3; } From 1d02c7796ebe545573272f577d7d9675f855dd03 Mon Sep 17 00:00:00 2001 From: Project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:44:22 -0600 Subject: [PATCH 5/5] test: park thousands of virtual threads in synchronized methods, a wait and plain frames --- test/java/VirtualPackedMix.java | 73 +++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 test/java/VirtualPackedMix.java diff --git a/test/java/VirtualPackedMix.java b/test/java/VirtualPackedMix.java new file mode 100644 index 0000000..45b09c9 --- /dev/null +++ b/test/java/VirtualPackedMix.java @@ -0,0 +1,73 @@ +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.locks.LockSupport; + +// thousands of parked virtual threads whose frames include synchronized methods +// and a wait, so packed frames sit next to frames that hold a monitor +public class VirtualPackedMix { + static final int COUNT = 2400; + static final CountDownLatch parked = new CountDownLatch(COUNT); + static final Object shared = new Object(); + static volatile boolean go; + + public static void main(String[] args) throws Exception { + long[] sums = new long[COUNT]; + Thread[] threads = new Thread[COUNT]; + for (int i = 0; i < COUNT; i++) { + int id = i; + threads[i] = Thread.ofVirtual().start(() -> sums[id] = switch (id % 3) { + case 0 -> new VirtualPackedMix().locked(id, 2.5 * id, "a" + id); + case 1 -> waiting(id); + default -> plain(id, 1L << 40, (float) id); + }); + } + parked.await(); + while (!allParked(threads)) Thread.sleep(10); + for (int id : new int[] {3, 4, 5}) { + StackTraceElement[] trace = threads[id].getStackTrace(); + boolean found = false; + for (StackTraceElement e : trace) found |= e.getMethodName().equals(id % 3 == 0 ? "locked" : id % 3 == 1 ? "waiting" : "plain"); + System.out.println("trace " + id + " " + found); + } + go = true; + synchronized (shared) { shared.notifyAll(); } + for (Thread t : threads) LockSupport.unpark(t); + long total = 0; + for (int i = 0; i < COUNT; i++) { + threads[i].join(); + total += sums[i]; + } + System.out.println("total " + total); + } + + static boolean allParked(Thread[] threads) { + for (Thread t : threads) if (t.getState() != Thread.State.WAITING) return false; + return true; + } + + synchronized long locked(int id, double d, String s) { + parked.countDown(); + while (!go) LockSupport.park(); + return id + (long) d + s.length(); + } + + static long waiting(int id) { + synchronized (shared) { + parked.countDown(); + while (!go) { + try { shared.wait(); } catch (InterruptedException e) { return -1; } + } + } + return id * 2L; + } + + static long plain(int id, long l, float f) { + return id + deeper(id, l, f); + } + + static long deeper(int id, long l, float f) { + long before = l + id; + parked.countDown(); + while (!go) LockSupport.park(); + return before + (long) f; + } +}