25.3. A node registry with WeakRef and FinalizationRegistry
Topics
This question is in
25. Memory and cleanupSome code needs to find objects by id: a list virtualizer looking up the row element for item 42, a devtools panel tracking every mounted view, a cache of decoded images. A Map from id to object works, but it keeps every object alive for as long as the map exists, even after the rest of the app has dropped it. A WeakMap cannot help, because you look up by id, not by the object. The tools for this are WeakRef, which refers to an object without keeping it alive, and FinalizationRegistry, which tells you some time after an object has been freed.
Write a NodeRegistry class in node-registry.js.
Signature
class NodeRegistry {
constructor(onCollect) // optional: onCollect(id), called when a registered node is freed
register(id, node) // returns the registry; replaces an earlier node for id
get(id) // the node, or undefined if unknown or freed
unregister(id) // true if id was registered with a live node
ids() // the ids of nodes still alive, in registration order
get size() // how many registered nodes are still alive
}Requirements
register(id, node)stores the node and returns the registry;get(id)returns it. An unknown id givesundefined. Ids can be any value.nodemust be an object (TypeErrorotherwise, and nothing is stored).onCollect, when given, must be a function (TypeError).- The node is held weakly: the registry keeps a
WeakRefto it, never the node itself (not in aMap, aSetor an array). Once the node is freed,getreturnsundefined. - When
get(orids) finds that a node is gone, it removes the entry at once, without waiting for a finalizer. - One
FinalizationRegistryserves the whole registry. Eachregisterregisters the node with it, with a held value that is not the node and with an unregister token. - When a registered node is freed, the finalizer removes its entry and calls
onCollect(id)once. This also happens whengetalready removed the entry. The finalizer never throws: ifonCollectthrows, the entry is still removed and the error is logged withconsole.error. unregister(id)removes the entry and cancels its finalizer, soonCollectis not called for it. It returns whether the id was registered with a live node, whether or notgetoridshas looked at it since the node was freed. It also cancels the finalizer of a dead entry thatgetoridsalready removed (and then returnsfalse).- Registering an id again replaces the node and cancels the old node's finalizer: freeing the old node must not remove the new entry or report the id. This holds even when the old node was already gone and
getoridshad removed its entry. - A finalizer for a replaced or unregistered registration that still runs (it was already queued) does nothing: it never removes a newer entry for the same id and never reports. A node registered under two ids reports both.
ids()lists the ids of live nodes in registration order;sizecounts them. Each registry is independent.
Examples
const rows = new NodeRegistry((id) => console.log("row freed", id));
const li = document.createElement("li");
rows.register(42, li);
rows.get(42) === li; // true
rows.size; // 1rows.register(42, otherLi); // replaces li, and cancels li's finalizer
rows.unregister(42); // true
rows.get(42); // undefinedrows.register(7, document.createElement("li"));
// No one else holds that element. Some time later the engine may free it:
rows.get(7); // undefined
// and, later still, "row freed 7" is logged.Environment
- Plain JavaScript in a browser page; the tests use the global
NodeRegistryclass fromnode-registry.js. - A test cannot make the garbage collector run. So most tests replace
WeakRefandFinalizationRegistrywith fakes for their duration: the fakes check their arguments like the real ones, and let the test mark an object as freed and then run the finalizers. Create both through the globals (new WeakRef(…),new FinalizationRegistry(…)) when the registry is constructed or used, not once when the file loads. One test uses the real built-ins. - Out of scope: holding the ids weakly, and anything that must happen when a node is freed (finalizers may run late or never).
Hints
- Finalizers can run long after a node was freed, and the id may have been reused by then. What could the held value be, so the callback can tell which registration it belongs to?
- Why must
gethandle a deadWeakRefitself, rather than rely on the finalizer?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it