Skip to content

Commit 2f0dc38

Browse files
committed
perf(runtime): weak collections learn rebuilt keyed canaries lazily
A private WeakMap maps every canary that stands for a key to that key, so lookups of canaries make no native call, and a value missing there was never a key. The runtime does not call into JS for each canary it builds for a keyed object: it counts them in a shared Int32Array, and the first lookup that misses while the count is nonzero takes them all in one call. The key lives on the object's canary record, where that call reads it, so keying an object no longer gives it a state. keyFor rules out plain JS objects first with maybeCanary, a V8 fast call, so set, add, register and new WeakRef make no native call for them. Each WeakRef keeps a native WeakRef to its canary for deref. A weakCollectionNativeCalls counter counts the calls into the runtime.
1 parent c787000 commit 2f0dc38

8 files changed

Lines changed: 518 additions & 84 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ wrapper.
104104
| `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. |
105105
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
106106
| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. |
107-
| `getWrapperClassCounts()` | Per Java class name (`<unknown>` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states`, which include those made only for a weak-collection key (see [Wrapper lifetime](#wrapper-lifetime)). |
107+
| `getWrapperClassCounts()` | Per Java class name (`<unknown>` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
108108
| `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). |
109109

110110
*Platform note (Android):* the original exception is the Java throwable `x`
@@ -189,16 +189,18 @@ every build on cold paths only:
189189
| `collected` | wrappers released because Java had collected their object |
190190
| `releasedExplicitly` | links released through `__releaseNativeCounterpart` |
191191
| `releasedAccesses` | lookups of the Java object of a wrapper whose link was released or whose Java object Java had already collected: calling its methods, using its fields or passing it to Java. Resolving an overloaded method looks its arguments up too, so one call can count more than once |
192-
| `canaryStates` | `"canary"` only: state objects created to hold JS properties, or to hold the key a weak collection made for the object, in which case no JS property was written |
192+
| `canaryStates` | `"canary"` only: state objects created to hold JS properties |
193193
| `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object |
194194
| `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Canaries without state have no handler |
195195
| `canaryCachedWrites` | `"canary"` only: of those writes, rewrites of a name the handler knew to be a plain data property of the state, mirrored with one store |
196196
| `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object |
197+
| `weakCollectionNativeCalls` | `"canary"` only: calls the weak collections make into the runtime: to make the key of a canary's Java object, to find the canary for a key, and to learn about canaries built for keyed objects since the last such call. Lookups of a value that was never a key make none |
197198

198199
In `"canary"` mode only array buffers backed by Java buffers resurrect;
199200
`weakened` counts objects held weakly because their canary died while they
200-
had a record (JS state, or a JS-extended instance), and `collected` counts
201-
canaries whose object had none, which Java no longer holds for JS.
201+
had a record (JS state, a weak-collection key, or a JS-extended instance),
202+
and `collected` counts canaries whose object had none, which Java no longer
203+
holds for JS.
202204

203205
`"canary"` is the resurrection-free model the iOS runtime and the Node-API
204206
runtimes share. Every wrapper of a Java object is a canary: a phantom-weak JS
@@ -273,21 +275,27 @@ on it, and lives as long as it does.
273275
old one without keeping it, so in canary mode a builtin
274276
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and
275277
`FinalizationRegistry` with subclasses that key a Java object whose wrapper is
276-
a canary by an opaque, frozen key its state holds. Entries and targets
277-
therefore live exactly as long as the Java object; `WeakRef.prototype.deref`
278+
a canary by an opaque, frozen key the object's record holds. Entries and
279+
targets therefore live exactly as long as the Java object; `WeakRef.prototype.deref`
278280
(and the `get` alias) returns the live canary, a new one with the object's
279281
state, or `undefined` once Java collected the object. `set`, `add`,
280-
`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do,
281-
so probing an object gives it no state. A Proxy around a Java object stays a
282+
`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do.
283+
Neither gives the object a state. A Proxy around a Java object stays a
282284
key of its own, and every other value passes through to the standard
283285
collection. The cost is the other side of the same rooting: a `WeakMap` value
284-
that references its Java key keeps the key, its state and so the Java object
286+
that references its Java key keeps the key, its record and so the Java object
285287
alive for as long as the map lives. And `deref` builds a canary, which holds
286288
the Java object strongly until it dies again, so a `WeakRef` to a Java object
287289
that is dereferenced on every frame or event may keep the object from ever
288-
being collected. In canary mode, an operation on an object costs a native
289-
call, and one that can create the key also checks its receiver first so that
290-
a call that fails leaves no key behind; that check names `has` (or
290+
being collected. In canary mode, an operation that can create the key costs a
291+
native call for a Java object the collection does not hold yet; a plain JS
292+
object costs only a V8 fast call that rules it out. Lookups (`get`, `has`,
293+
`delete`, `unregister`, `deref`) make no native call, except a `deref` that
294+
has to build a canary, and the first lookup that misses after the runtime
295+
built canaries for keyed objects, which makes one call for all of them. An
296+
operation that can create the
297+
key also checks its receiver first so that a call that fails leaves no key
298+
behind; that check names `has` (or
291299
`unregister`) in its `TypeError`. The collections are subclasses of the
292300
standard ones, which shows: `Object.getPrototypeOf(WeakMap.prototype)` is the
293301
standard prototype, and `WeakMap.toString()` is not native code.

‎test-app/app/src/main/assets/app/tests/testWrapperLifetime.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ describe("Wrapper lifetime", function () {
3838
var stats = runtime.getWrapperLifetimeStats();
3939
expect(Object.keys(stats).sort()).toEqual(
4040
["canaryCachedWrites", "canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds",
41-
"canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]);
41+
"canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections",
42+
"weakCollectionNativeCalls", "weakened"]);
4243
Object.keys(stats).forEach(function (key) {
4344
expect(typeof stats[key]).toBe("number");
4445
});

‎test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,18 @@ describe("Weak collections of Java objects", function () {
349349
}, 0);
350350
}, 20000);
351351

352+
it("gives no state to a Java object it only keys", function () {
353+
var map = new WeakMap();
354+
var set = new WeakSet();
355+
var builder = new java.lang.StringBuilder("keyed");
356+
var states = runtime.getWrapperLifetimeStats().canaryStates;
357+
map.set(builder, 1);
358+
set.add(builder);
359+
expect(map.get(builder)).toBe(1);
360+
expect(set.has(builder)).toBe(true);
361+
expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states);
362+
});
363+
352364
it("makes no key for a call the standard collection rejects", function () {
353365
var runnable = new java.lang.Runnable({ run: function () {} });
354366
var registry = new FinalizationRegistry(function () {});
@@ -402,6 +414,187 @@ describe("Weak collections of Java objects", function () {
402414
}).toThrowError(TypeError, /invalid target/);
403415
});
404416

417+
// A canary built for an object that has a key, by any path (here a Java field read, not
418+
// a deref), stands for the key at once; a canary that was never a key makes no state.
419+
it("finds what was keyed on a Java object through a canary built by a Java read", function (done) {
420+
var map = new WeakMap();
421+
var set = new WeakSet();
422+
var registry = new FinalizationRegistry(function () {});
423+
var token = new java.lang.StringBuilder("token");
424+
var NativeWeakRef = Object.getPrototypeOf(WeakRef) === Function.prototype ? WeakRef : Object.getPrototypeOf(WeakRef);
425+
var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds;
426+
var firstCanaries;
427+
var refs = (function () {
428+
var plain = new java.lang.StringBuilder("plain");
429+
map.set(plain, "plain value");
430+
set.add(plain);
431+
var runnable = new java.lang.Runnable({ run: function () {} });
432+
registry.register(runnable, "held", plain);
433+
map.set(runnable, "extended value");
434+
var list = new java.util.ArrayList();
435+
list.add(plain);
436+
list.add(runnable);
437+
Holder.held = list;
438+
firstCanaries = [new NativeWeakRef(plain), new NativeWeakRef(runnable)];
439+
return [new WeakRef(plain), new WeakRef(runnable)];
440+
})();
441+
setTimeout(function () {
442+
collectBoth();
443+
if (canary) {
444+
// A plain wrapper is a canary under scope "all" only.
445+
if (runtime.getConfig("wrapperLifetimeScope") === "all") {
446+
expect(firstCanaries[0].deref()).toBeUndefined();
447+
}
448+
expect(firstCanaries[1].deref()).toBeUndefined();
449+
}
450+
var list = Holder.held;
451+
var held = [list.get(0), list.get(1)];
452+
if (canary) {
453+
expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds);
454+
}
455+
expect(map.get(held[0])).toBe("plain value");
456+
expect(set.has(held[0])).toBe(true);
457+
expect(map.get(held[1])).toBe("extended value");
458+
expect(refs[0].deref() === held[0]).toBe(true);
459+
expect(refs[1].deref() === held[1]).toBe(true);
460+
expect(refs[1].deref() === refs[1].deref()).toBe(true);
461+
expect(registry.unregister(held[0])).toBe(true);
462+
expect(set.delete(held[0])).toBe(true);
463+
expect(set.has(held[0])).toBe(false);
464+
expect(map.delete(held[1])).toBe(true);
465+
expect(map.has(held[1])).toBe(false);
466+
var states = runtime.getWrapperLifetimeStats().canaryStates;
467+
expect(map.has(token)).toBe(false);
468+
expect(map.get(token)).toBeUndefined();
469+
expect(set.delete(token)).toBe(false);
470+
expect(registry.unregister(token)).toBe(false);
471+
expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states);
472+
var plainTarget = {};
473+
expect(new WeakRef(plainTarget).deref()).toBe(plainTarget);
474+
done();
475+
}, 0);
476+
});
477+
478+
// Keying a canary must not keep it alive: only WeakRef construction and deref do, until
479+
// the job ends, as the standard says.
480+
it("lets a canary that was just keyed die in the same job", function () {
481+
var map = new WeakMap();
482+
var set = new WeakSet();
483+
var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds;
484+
(function () {
485+
var runnable = heldRunnable();
486+
map.set(runnable, "value");
487+
set.add(runnable);
488+
})();
489+
collectBoth();
490+
expect(map.get(Holder.held)).toBe("value");
491+
expect(set.has(Holder.held)).toBe(true);
492+
if (canary) {
493+
expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds);
494+
}
495+
});
496+
497+
function nativeCalls() {
498+
return runtime.getWrapperLifetimeStats().weakCollectionNativeCalls;
499+
}
500+
501+
it("never calls into the runtime for plain JS objects or lookups of values that were never keys", function () {
502+
var map = new WeakMap();
503+
var set = new WeakSet();
504+
var registry = new FinalizationRegistry(function () {});
505+
var plain = {};
506+
var other = {};
507+
map.set(plain, 1);
508+
set.add(plain);
509+
registry.register(plain, "held", plain);
510+
var ref = new WeakRef(plain);
511+
var javaObject = new java.lang.Object();
512+
var runnable = new java.lang.Runnable({ run: function () {} });
513+
// A miss takes whatever canaries earlier specs left to be told about.
514+
map.has({});
515+
var before = nativeCalls();
516+
expect(map.get(plain)).toBe(1);
517+
expect(map.has(other)).toBe(false);
518+
expect(map.get(other)).toBeUndefined();
519+
expect(map.delete(other)).toBe(false);
520+
expect(set.has(plain)).toBe(true);
521+
expect(set.has(other)).toBe(false);
522+
expect(set.delete(other)).toBe(false);
523+
expect(ref.deref()).toBe(plain);
524+
expect(ref.get()).toBe(plain);
525+
expect(registry.unregister(other)).toBe(false);
526+
map.set(plain, 2);
527+
set.add(plain);
528+
expect(map.has(javaObject)).toBe(false);
529+
expect(map.get(runnable)).toBeUndefined();
530+
expect(set.has(runnable)).toBe(false);
531+
expect(registry.unregister(runnable)).toBe(false);
532+
var fresh = {};
533+
map.set(fresh, 3);
534+
set.add(fresh);
535+
registry.register(fresh, "fresh", fresh);
536+
expect(new WeakRef(fresh).deref()).toBe(fresh);
537+
expect(map.getOrInsert ? map.getOrInsert({}, 4) : 4).toBe(4);
538+
expect(nativeCalls()).toBe(before);
539+
});
540+
541+
// The runtime only counts the canaries it builds for keyed objects; the first lookup
542+
// that misses learns them all with one call.
543+
it("finds a keyed Java object through canaries built while no lookup ran", function () {
544+
var map = new WeakMap();
545+
var set = new WeakSet();
546+
var registry = new FinalizationRegistry(function () {});
547+
var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds;
548+
(function () {
549+
var runnable = heldRunnable();
550+
map.set(runnable, "value");
551+
set.add(runnable);
552+
registry.register(runnable, "held", runnable);
553+
})();
554+
collectBoth();
555+
(function () {
556+
expect(set.has(Holder.held)).toBe(true);
557+
})();
558+
collectBoth();
559+
// Built and dead again before any lookup saw it.
560+
(function () {
561+
Holder.held.hashCode();
562+
})();
563+
collectBoth();
564+
var again = Holder.held;
565+
if (canary) {
566+
expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds + 2);
567+
}
568+
var before = nativeCalls();
569+
expect(map.has({})).toBe(false);
570+
if (canary) {
571+
expect(nativeCalls()).toBe(before + 1);
572+
}
573+
expect(map.has({})).toBe(false);
574+
expect(map.get(again)).toBe("value");
575+
expect(set.has(again)).toBe(true);
576+
expect(registry.unregister(again)).toBe(true);
577+
if (canary) {
578+
expect(nativeCalls()).toBe(before + 1);
579+
}
580+
});
581+
582+
it("finds a keyed Java object through a canary built and released while no lookup ran", function () {
583+
var map = new WeakMap();
584+
var set = new WeakSet();
585+
(function () {
586+
var runnable = heldRunnable();
587+
map.set(runnable, "value");
588+
set.add(runnable);
589+
})();
590+
collectBoth();
591+
var released = Holder.held;
592+
__releaseNativeCounterpart(released);
593+
expect(set.has(released)).toBe(true);
594+
expect(map.get(released)).toBe("value");
595+
expect(map.has({})).toBe(false);
596+
});
597+
405598
it("installs the canary collections only in canary mode", function () {
406599
var native = WeakMap.toString().indexOf("[native code]") !== -1;
407600
expect(native).toBe(!canary);

‎test-app/runtime/src/main/cpp/NsBuiltinModules.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo<Value>& info) {
175175
set("collected", stats.collected);
176176
set("releasedExplicitly", stats.releasedExplicitly);
177177
set("releasedAccesses", stats.releasedAccesses);
178+
set("weakCollectionNativeCalls", stats.weakCollectionNativeCalls);
178179
set("canaryStates", stats.canaryStates);
179180
set("canaryNativeDeaths", stats.canaryNativeDeaths);
180181
set("canaryInterceptedWrites", stats.canaryInterceptedWrites);

0 commit comments

Comments
 (0)