Sub topic 10
What the Engine Does Not Promise
This chapter assumes you already know how to create a WeakRef, call deref(), and register objects with a FinalizationRegistry. It also assumes you understand the event loop at a conceptual level, in particular what a "job" (one run of synchronous code from start to finish) is. The topic here is the gap between what these APIs appear to offer and what the specification actually guarantees.
The short list of guarantees
The ECMAScript specification guarantees very little about weak references:
- A target you dereferenced stays alive until the current job finishes. Two
deref()calls in the same synchronous run give the same answer. - Cleanup callbacks never run in the middle of synchronous code. They are scheduled as separate tasks.
- A
WeakRefto a collected target returnsundefinedfromderef(). It never returns a different object.
The rest is left to the engine.
What is explicitly not promised
| Assumption | Reality |
|---|---|
| An unreachable object will be collected | It may never be collected. The engine might not need the memory. |
| Collection happens soon after an object becomes unreachable | It can take seconds, minutes, or never happen. |
| The cleanup callback runs after collection | The spec permits engines to skip it entirely. |
| Callbacks run before the program exits | Closing a tab or ending a Node.js process can drop pending callbacks. |
| Callbacks run in registration order | No ordering is specified across targets. |
| Engines behave the same way | V8, SpiderMonkey, and JavaScriptCore use different collectors and heuristics. |
| Behavior is stable across versions | A browser update can change when collection happens. |
If the registry object becomes unreachable, its callbacks may also stop running, because nothing keeps the registry alive on your behalf.
A program that relies on a broken assumption
This code expects the callback to run soon after the object is released. Run it with plain node, without flags:
const registry = new FinalizationRegistry((label) => {
console.log(`finalized ${label}`);
});
let saved = false;
(function () {
const data = { payload: new Array(1000).fill('x') };
registry.register(data, 'data-1');
})();
setTimeout(() => {
// Wrong: assumes the callback has had a chance to run.
if (!saved) {
console.log('Callback never ran; nothing was saved.');
}
}, 1000);On most runs it prints "Callback never ran; nothing was saved." and then exits. One second with very little memory pressure gives V8 no reason to collect anything. The exact result can change between runs and between Node.js versions, and that unpredictability is the reason not to depend on it.
Why the specification is this loose
Collectors use generational, incremental, and concurrent strategies. If the spec required prompt or exact finalization, engines would have to scan more often or track objects more precisely, and every program would get slower. Leaving timing unspecified keeps the collector free to choose. The cost is that your code gets no timing information from it.
Reasonable uses that survive these limits
Code that stays correct whether or not the callback runs is safe:
- Removing stale entries from a cache, where a leftover entry only wastes a little memory.
- Logging a warning that a resource was not closed explicitly, as a debugging aid.
- Releasing a resource as a backup, when an explicit
close()already handles the normal path.
Exercise
A team uses a FinalizationRegistry callback to decrement a counter of "active sessions," and an admin page displays that counter. Why is this design unreliable, and what should they do instead?
Show answer
The engine may collect session objects late or never, and may skip the callback even after collection, so the counter can stay too high indefinitely and differ between browsers or runtime versions. They should decrement the counter in an explicit end-session method (for example close() or logout()). At most, the registry can log a warning for sessions that were never closed.
Exercise
Within one synchronous function, you call ref.deref() twice. The first call returns an object. Can the second call return undefined?
Show answer
No. A target returned by deref() is kept alive until the end of the current job, so both calls in the same synchronous run return the same object.