Skip to content

Commit cead124

Browse files
authored
Save warm library VMs, so javac's first compile skips its cold start (#48)
1 parent 509713f commit cead124

17 files changed

Lines changed: 584 additions & 43 deletions

File tree

‎docs/browser.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ and `cjFileBlob(path)` also work.
3535
has no environment otherwise. Under Node, Java sees the host's environment.
3636
- `preloadProgress(done, total)` reports the bytes of the runtime downloaded at start.
3737
`total` is 0 while the server has not sent a length; the last call has `done === total`.
38+
- `cheerpjInit({ warmSnapshot: true })` saves a library VM once its calls have warmed it up (see below).
3839
- A file Java closes under `/files/downloads/` is downloaded by the browser.
3940
`/files/uploads/` exists for files the page adds there.
4041
- The browser console gets whole lines, so two `print` calls and a `println` log one
@@ -126,3 +127,12 @@ After a VM boots, the worker keeps a snapshot of it, in memory and in
126127
IndexedDB (the 4 most recently used). Later runs with the same class path and
127128
`cheerpjInit` options start from it instead of booting, in this page and in
128129
later visits.
130+
131+
With `warmSnapshot: true`, `cheerpjRunLibrary` also saves its VM after a call
132+
returns once its calls have loaded at least 200 classes since boot (one javac
133+
compile loads over a thousand) and no library handles are live. Later library
134+
starts with the same class path restore that image, after checking that the
135+
files, missing paths and directory listings those calls used are unchanged; the
136+
first javac compile after it took 2.7 s instead of 5.3 s in Chromium on a
137+
Raspberry Pi 5. An image is about 18 MB. IndexedDB keeps the 2 most recent warm images separately
138+
from boot snapshots.

‎docs/node.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ resolves to the exit code. Its options:
5252
- `fetch`: sockets stay inside the VM, and `http:` requests go to this `fetch`, as in the browser
5353

5454
- `snapshotDir`: where boot snapshots are kept, or `null` for none (see below)
55+
- `warmSnapshot: true`: save a library VM once its calls have warmed it up (see below)
5556

5657
`startLibrary(options)` starts a VM in library mode, and `libraryOf(vm)` is its
5758
`lib`, used as `cheerpjRunLibrary`'s result is in the browser. `vm.halt(0)`
@@ -67,3 +68,13 @@ reads all of them. The snapshots, about 1 MB each, are kept in
6768
`$XDG_CACHE_HOME/java-web/snapshots` (`~/.cache/java-web/snapshots`), the 16
6869
most recently used. Set `JAVA_WEB_SNAPSHOT_DIR` to keep them elsewhere, or to
6970
an empty value to turn them off.
71+
72+
Set `warmSnapshot: true` in `startLibrary` options to save the VM after a call
73+
returns once its calls have loaded at least 200 classes since boot (one javac
74+
compile loads over a thousand) and no library handles are live. A later library
75+
start with the same class path and working directory restores it, after
76+
checking that the files, missing paths and directory listings those calls used
77+
are unchanged; a javac compile from it takes about 1 s instead of 6 s on a
78+
Raspberry Pi 5. An image is about 18 MB; warm snapshots share the snapshot
79+
directory and keep the 2 most recent. They build on boot snapshots, so with
80+
`snapshotDir: null` there are none.

‎src/browser/api.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ export interface InitOptions {
2929
env?: string[];
3030
// load the formats and names of locales other than English
3131
localeData?: boolean;
32+
// save and restore library VMs after their first idle call
33+
warmSnapshot?: boolean;
3234
// where java-web.js, the worker and jdk/ live; defaults to the script's directory
3335
runtime?: string;
3436
// receives output instead of the page console element
@@ -178,7 +180,7 @@ export function cheerpjInit(options: InitOptions = {}): Promise<void> {
178180
};
179181
});
180182
natives = options.natives ?? {};
181-
send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, natives: Object.keys(natives), progress: !!options.preloadProgress });
183+
send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, warmSnapshot: !!options.warmSnapshot, natives: Object.keys(natives), progress: !!options.preloadProgress });
182184
initStarted(ready);
183185
return ready;
184186
}

‎src/browser/idb.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@
33
// changes are written back in batches.
44

55
import type { MemoryBackend, MemoryEntry } from "../fs.ts";
6-
import type { SnapshotImage } from "../snapshot.ts";
6+
import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts";
77

88
const DB = "java-web", STORE = "files";
99
// its own database, so adding it needs no version change that open pages would block
1010
const SNAPSHOT_DB = "java-web-snapshots";
1111
// snapshot keys, most recently used first
1212
const ORDER = "#order";
13-
const KEEP_SNAPSHOTS = 4;
13+
const WARM_ORDER = "#warm-order";
14+
const KEEP_SNAPSHOTS = 4, KEEP_WARM_SNAPSHOTS = 2;
1415

1516
function request<T>(r: IDBRequest<T>): Promise<T> {
1617
return new Promise((resolve, reject) => {
@@ -108,3 +109,35 @@ export function saveSnapshot(image: SnapshotImage) {
108109
export function dropSnapshot(key: string) {
109110
useSnapshot(key, null).catch(() => {});
110111
}
112+
113+
async function useWarmSnapshot(key: string, image?: WarmSnapshotImage | null) {
114+
const db = await openSnapshots();
115+
if (!db) return;
116+
const store = db.transaction(STORE, "readwrite").objectStore(STORE);
117+
const id = `warm:${key}`;
118+
if (image) store.put(image, id);
119+
const order = ((await request(store.get(WARM_ORDER))) as string[] | undefined ?? []).filter((k) => k !== id);
120+
if (image !== null) order.unshift(id);
121+
for (const k of [...order.slice(KEEP_WARM_SNAPSHOTS), ...(image === null ? [id] : [])]) store.delete(k);
122+
store.put(order.slice(0, KEEP_WARM_SNAPSHOTS), WARM_ORDER);
123+
}
124+
125+
export async function loadWarmSnapshot(key: string): Promise<WarmSnapshotImage | null> {
126+
try {
127+
const db = await openSnapshots();
128+
if (!db) return null;
129+
const id = `warm:${key}`;
130+
const image = (await request(db.transaction(STORE, "readonly").objectStore(STORE).get(id))) as WarmSnapshotImage | undefined;
131+
if (!image) return null;
132+
useWarmSnapshot(key).catch(() => {});
133+
return image;
134+
} catch { return null; }
135+
}
136+
137+
export function saveWarmSnapshot(image: WarmSnapshotImage) {
138+
useWarmSnapshot(image.warmKey, image).catch(() => {});
139+
}
140+
141+
export function dropWarmSnapshot(key: string) {
142+
useWarmSnapshot(key, null).catch(() => {});
143+
}

‎src/browser/protocol.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export interface InitMessage {
1212
hostName?: string;
1313
env: Record<string, string>;
1414
localeData: boolean;
15+
warmSnapshot: boolean;
1516
// JNI names of natives the page implements
1617
natives: string[];
1718
// report the download of the runtime

‎src/browser/worker.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
import { MemoryBackend, VFS } from "../fs.ts";
66
import { JVM, SnapshotError } from "../jvm.ts";
77
import { HttpBackend, parsePack } from "./http.ts";
8-
import { dropSnapshot, loadSnapshot, persist, saveSnapshot } from "./idb.ts";
9-
import type { SnapshotImage } from "../snapshot.ts";
8+
import { dropSnapshot, dropWarmSnapshot, loadSnapshot, loadWarmSnapshot, persist, saveSnapshot, saveWarmSnapshot } from "./idb.ts";
9+
import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts";
1010
import type { LibraryError, LibraryReply } from "../library.ts";
1111
import type { NativeReply } from "../bridge.ts";
1212
import type { FromWorker, InitMessage, ToWorker } from "./protocol.ts";
@@ -113,6 +113,8 @@ declare const JAVA_WEB_BUILD: string;
113113
// in IndexedDB for later loads. A VM changes the image it restores, so each
114114
// gets a copy.
115115
const snapshots = new Map<string, SnapshotImage>();
116+
const warmSnapshots = new Map<string, WarmSnapshotImage>();
117+
const droppedWarmSnapshots = new Set<string>();
116118
const keep = (image: SnapshotImage) => {
117119
snapshots.delete(image.key);
118120
snapshots.set(image.key, image);
@@ -143,6 +145,29 @@ const snapshotCache = {
143145
},
144146
};
145147

148+
const warmSnapshotCache = {
149+
load: async (key: string) => {
150+
if (droppedWarmSnapshots.has(key)) return null;
151+
const image = warmSnapshots.get(key) ?? await loadWarmSnapshot(key);
152+
if (!image) return null;
153+
warmSnapshots.delete(key);
154+
warmSnapshots.set(key, image);
155+
return structuredClone(image);
156+
},
157+
save: (image: WarmSnapshotImage) => {
158+
droppedWarmSnapshots.delete(image.warmKey);
159+
warmSnapshots.delete(image.warmKey);
160+
warmSnapshots.set(image.warmKey, structuredClone(image));
161+
for (const k of [...warmSnapshots.keys()].slice(0, -2)) warmSnapshots.delete(k);
162+
saveWarmSnapshot(image);
163+
},
164+
drop: (key: string) => {
165+
warmSnapshots.delete(key);
166+
droppedWarmSnapshots.add(key);
167+
dropWarmSnapshot(key);
168+
},
169+
};
170+
146171
// A snapshot that cannot be restored is dropped, and a second VM boots.
147172
function retried<T>(start: () => Promise<T>): Promise<T> {
148173
return start().catch((e) => {
@@ -152,9 +177,10 @@ function retried<T>(start: () => Promise<T>): Promise<T> {
152177
});
153178
}
154179

155-
function newVm(classpath: string[], vmId: number): JVM {
180+
function newVm(classpath: string[], vmId: number, library = false): JVM {
156181
return new JVM({
157182
snapshots: snapshotCache,
183+
...(library && config!.warmSnapshot ? { warmSnapshot: true, warmSnapshots: warmSnapshotCache } : {}),
158184
fs: vfs!,
159185
javaHome: "/jdk",
160186
classpath,
@@ -226,7 +252,7 @@ self.onmessage = (e: MessageEvent<ToWorker>) => {
226252
}
227253
case "library": {
228254
reply(m.id, retried(() => {
229-
const vm = newVm(m.classpath, m.lib);
255+
const vm = newVm(m.classpath, m.lib, true);
230256
vms.set(m.lib, vm);
231257
return vm.startLibrary();
232258
}).then(() => ({ value: undefined })));

0 commit comments

Comments
 (0)