Sub topic 11
WeakRef and FinalizationRegistry, and Why to Avoid Relying on Them
This chapter assumes you know how reachability decides what the collector keeps, how mark-and-sweep works, and how WeakMap and WeakSet hold keys weakly. You should also be able to run scripts in Node.js with command-line flags.
WeakMap lets you attach data to an object without keeping it alive, but it never tells you whether the object still exists. Two newer APIs, added in ES2021, do expose that information:
WeakRefis a weak reference to a single object. You can ask whether the object is still there.FinalizationRegistrylets you register a callback that may run after an object has been collected.
Both APIs make garbage collection visible to your code. The collector's timing is unspecified and differs between engines, versions, and runs. That makes these APIs easy to misuse. The TC39 proposal itself says "avoid them if possible." This chapter shows how they work, the few cases where they help, and the failure modes that make them a poor base for correctness.
How WeakRef works
A WeakRef wraps a target object. The wrapper does not count toward reachability. If the only remaining paths to the target go through WeakRef instances, the collector is free to reclaim it.
You read the target with deref(). It returns the object if it still exists and undefined if it has been collected.
let config = { theme: "dark" };
const ref = new WeakRef(config);
const current = ref.deref();
if (current !== undefined) {
console.log(current.theme); // "dark"
}
config = null; // now only the WeakRef points at the objectThe target must be an object or a non-registered symbol. Passing a primitive such as a string or number throws a TypeError, because primitives have no identity to track.
The target is stable for the rest of the current job
The specification adds a guarantee that prevents a target from disappearing mid-function. When you create a WeakRef or call deref() and get an object back, the engine keeps that target alive until the current synchronous job finishes. A job is the run of code until control returns to the event loop.
So this pattern is safe:
function render(ref) {
const node = ref.deref();
if (!node) return;
// node cannot be collected between these lines
node.textContent = "updated";
node.classList.add("fresh");
}The guarantee also has a side effect. A deref() that returns undefined can only happen in a later job. If you create a WeakRef, drop the strong reference, and check deref() on the next line, you will always get the object back. Tests that expect collection inside a single synchronous block will never pass.
How FinalizationRegistry works
A FinalizationRegistry is created with a cleanup callback. You register objects with it, and each registration carries a held value. After a registered object is collected, the engine may queue the callback with that held value.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`cleanup for ${heldValue}`);
});
let session = { id: 42 };
const token = {};
registry.register(session, "session 42", token);
// If you clean up manually, cancel the pending callback:
registry.unregister(token); // returns true if a registration was removedThe register(target, heldValue, unregisterToken) arguments have strict rules:
| Argument | Purpose | Rule |
|---|---|---|
| `target` | The object being watched | Held weakly. Must be an object or non-registered symbol. |
| `heldValue` | Passed to the callback | Held strongly. Must not be the target, or `register` throws. |
| `unregisterToken` | Key for `unregister()` | Held weakly. Optional. Often the target itself or a wrapper. |
The held value is held strongly, and the reason matters. If the held value refers to the target, even indirectly through a property, the target stays reachable from the registry and is never collected. The engine catches only the direct case register(obj, obj). It cannot catch register(obj, { owner: obj }), which leaks silently.
The callback lifecycle
Each arrow after WeaklyReachable is something the engine may do. None of them is something it must do.
Why you cannot rely on them
The specification makes almost no promises about timing. These cases are all allowed:
- The callback never runs. A short script can finish before any major collection happens. A browser tab can close with callbacks still queued. Node.js does not run pending finalizers on exit.
- Collection happens much later than you expect. V8 promotes long-lived objects to the old generation, which is collected rarely. An object can sit there, unreachable, for minutes.
- Collection happens earlier than you expect. An optimizing compiler can find that a variable is never read again and treat its object as dead before the variable leaves scope.
- Behavior differs across engines. V8, SpiderMonkey, and JavaScriptCore use different heuristics. Code that "works" in Chrome may never trigger cleanup in Safari.
- Callbacks run in their own task. They do not run during your code, and if one throws, the error is reported like any uncaught exception. No caller can catch it.
The practical rule: if your program gives wrong results when a finalizer never runs, the design is broken. Finalizers can only be an optimization or a safety net.
Observing collection in Node.js
To experiment, Node.js can expose a manual gc() function with the --expose-gc flag. Even then, callbacks run in a later task, and the target must not be held by the current job.
// Run with: node --expose-gc weakref-demo.js
const registry = new FinalizationRegistry((label) => {
console.log(`finalized: ${label}`);
});
let target = { payload: new Array(100_000).fill(1) };
const ref = new WeakRef(target);
registry.register(target, "big object");
target = null;
// Wait for a new job so the WeakRef no longer keeps the target alive.
setTimeout(() => {
globalThis.gc();
setTimeout(() => {
console.log("deref after gc:", ref.deref());
}, 0);
}, 0);On current Node.js versions this usually prints deref after gc: undefined and finalized: big object. The order of the two lines can vary. Without --expose-gc the script will most likely exit before any collection and print the object, with no finalization line. That difference is the whole lesson: what you see depends on whether the collector happened to run.
A legitimate use: a cache of weakly held values
WeakMap holds keys weakly, but sometimes you need the opposite. You want to look up by a string or number key and hold the value weakly. A typical example is a cache of decoded images keyed by URL. If nothing else uses an image, it can be reclaimed, and the cache will rebuild it on demand.
WeakRef holds the values. FinalizationRegistry removes dead entries so the Map does not fill up with empty wrappers.
class WeakValueCache {
#entries = new Map();
#registry = new FinalizationRegistry((key) => {
const ref = this.#entries.get(key);
// Only delete if the entry still points at a dead object.
// A newer value may have been stored under the same key.
if (ref !== undefined && ref.deref() === undefined) {
this.#entries.delete(key);
}
});
get(key) {
return this.#entries.get(key)?.deref();
}
set(key, value) {
const previous = this.#entries.get(key);
if (previous !== undefined) {
this.#registry.unregister(previous);
}
const ref = new WeakRef(value);
this.#entries.set(key, ref);
this.#registry.register(value, key, ref); // ref is the unregister token
}
get size() {
return this.#entries.size;
}
}
function loadExpensive(id) {
return { id, data: new Array(10_000).fill(id) };
}
const cache = new WeakValueCache();
function getItem(id) {
let item = cache.get(id);
if (item === undefined) {
item = loadExpensive(id);
cache.set(id, item);
}
return item;
}
console.log(getItem(1).id); // 1, loaded
console.log(getItem(1).id); // 1, likely from cache
console.log(cache.size); // 1Several details in this class follow from the earlier rules:
getItemstays correct whether or not the value was collected, because a miss just reloads. The finalizer only keeps theMapsmall.- The callback checks
deref()before deleting. Without that check, a late callback for an old value could delete a fresh entry stored under the same key. - The held value is the key, a primitive, which cannot accidentally refer back to the target.
- The
WeakRefserves as the unregister token, sosetcan cancel the old registration.
A weak cache does not replace a size-bounded cache. A V8 collection can drop every entry at once, and the cache empties exactly when memory gets tight. Most applications get more predictable results from an LRU cache with a fixed maximum size. Use weak values when the data is already kept alive by something else, such as objects currently shown on screen, and the cache only deduplicates them.
Choosing the right tool
| Goal | Use | Why |
|---|---|---|
| Attach data to an object you don't own | `WeakMap` | Deterministic API, no timing exposed |
| Track "seen" objects | `WeakSet` | Same as above |
| Cache values by a primitive key, without pinning them | `WeakRef` + `FinalizationRegistry` | Only pattern where values must be weak |
| Bound memory use predictably | LRU cache with a size limit | Eviction you can reason about and test |
| Release files, sockets, or handles | Explicit `close()` / `try...finally` | Must happen at a known time |
| Detect resources that were never closed | `FinalizationRegistry` logging | Best-effort diagnostics are acceptable |
If you reach for WeakRef first, check whether a WeakMap or an explicit teardown method solves the problem. Usually one does.
Exercise
A developer writes registry.register(conn, { connection: conn, openedAt: Date.now() }) so the cleanup callback can log which connection leaked. Why will the callback never run for these connections, and how should the code change?
Show answer
The held value is held strongly by the registry, and it contains a property pointing to conn. The registry therefore keeps every connection reachable, so none is ever collected. The engine only rejects the direct case where the held value is the target itself. The fix is to pass data that does not reference the target, such as { id: conn.id, openedAt: Date.now() } or just the id string.
Exercise
A test creates const ref = new WeakRef(obj), sets obj = null, calls globalThis.gc() on the next line under --expose-gc, then asserts ref.deref() === undefined. The assertion fails. Why?
Show answer
Creating a WeakRef adds its target to the set of objects kept alive until the current synchronous job ends. The gc() call and the assertion run in the same job, so the target cannot be collected yet. The test must yield to the event loop, for example with setTimeout or await new Promise(r => setTimeout(r, 0)), before calling gc() and checking. Even then, the result depends on the engine, so a production test should not assert on collection at all.
Exercise
In the WeakValueCache class, what could go wrong if the finalization callback deleted this.#entries.delete(key) without first checking ref.deref() === undefined?
Show answer
Suppose value A is stored under key "x", then replaced by value B. If A's finalization callback was already queued before unregister ran, or if unregister was skipped, the callback would run later with key "x" and delete the entry holding the live value B. The check makes sure only an entry whose target is really gone gets removed.