Skip to curriculum
Jump to the editor

25.3. A node registry with WeakRef and FinalizationRegistry

Hard
Topics

This question is in

25. Memory and cleanup
30–45 min

Some 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

JAVASCRIPT
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

  1. register(id, node) stores the node and returns the registry; get(id) returns it. An unknown id gives undefined. Ids can be any value.
  2. node must be an object (TypeError otherwise, and nothing is stored). onCollect, when given, must be a function (TypeError).
  3. The node is held weakly: the registry keeps a WeakRef to it, never the node itself (not in a Map, a Set or an array). Once the node is freed, get returns undefined.
  4. When get (or ids) finds that a node is gone, it removes the entry at once, without waiting for a finalizer.
  5. One FinalizationRegistry serves the whole registry. Each register registers the node with it, with a held value that is not the node and with an unregister token.
  6. When a registered node is freed, the finalizer removes its entry and calls onCollect(id) once. This also happens when get already removed the entry. The finalizer never throws: if onCollect throws, the entry is still removed and the error is logged with console.error.
  7. unregister(id) removes the entry and cancels its finalizer, so onCollect is not called for it. It returns whether the id was registered with a live node, whether or not get or ids has looked at it since the node was freed. It also cancels the finalizer of a dead entry that get or ids already removed (and then returns false).
  8. 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 get or ids had removed its entry.
  9. 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.
  10. ids() lists the ids of live nodes in registration order; size counts them. Each registry is independent.

Examples

JAVASCRIPT
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;             // 1
JAVASCRIPT
rows.register(42, otherLi);   // replaces li, and cancels li's finalizer
rows.unregister(42);          // true
rows.get(42);                 // undefined
JAVASCRIPT
rows.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 NodeRegistry class from node-registry.js.
  • A test cannot make the garbage collector run. So most tests replace WeakRef and FinalizationRegistry with 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

  1. 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?
  2. Why must get handle a dead WeakRef itself, 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
Back to the question
Loading the editor…