Sub topic 2
Why a deref()'d Target Survives the Current Job
This chapter assumes you know closures, have a rough picture of the event loop, and have already created a WeakRef with deref().
Why a deref()'d Target Survives the Current Job
When you create a WeakRef, or when deref() returns an object, the engine adds that object to an internal "kept-alive" list. The engine clears this list only after the current synchronous job has finished. A job is one run of a script, a task, or a callback. Inside a single job, the target cannot disappear between two deref() calls:
const ref = new WeakRef({ name: 'data' });
const a = ref.deref();
const b = ref.deref();
console.log(a === b); // true within the same jobThis guarantee ends at an await or a setTimeout. After either one, call deref() again and check the result for undefined.
FinalizationRegistry and Cleanup Callbacks
A FinalizationRegistry takes a cleanup callback. After a registered object has been collected, the engine may call that callback.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Cleaned up: ${heldValue}`);
});
let resource = { id: 42 };
registry.register(resource, 'resource-42');
resource = null;Held Values: Passing Data to the Callback
The callback never receives the target, because the target is already gone. It receives the held value, which is the second argument you passed to register(). The registry holds this value strongly, so it must not refer back to the target. If it does, the target can never be collected. Passing the target itself as the held value throws an error:
const registry = new FinalizationRegistry(() => {});
const obj = {};
try {
registry.register(obj, obj);
} catch (err) {
console.log(err instanceof TypeError); // true
}Cancelling Registrations with Unregister Tokens
The optional third argument to register() is an unregister token. It must be an object or a non-registered symbol, and the registry holds it weakly. Passing the same token to unregister() cancels the registration and returns true if anything was removed. A common choice is to use the wrapper object itself as the token:
const registry = new FinalizationRegistry((handle) => handle.close());
class Wrapper {
constructor(handle) {
this.handle = handle;
registry.register(this, handle, this);
}
close() {
registry.unregister(this);
this.handle.close();
}
}
const w = new Wrapper({ close: () => console.log('closed') });
w.close(); // prints "closed" once; finalization is cancelledWhat the Engine Does Not Promise
| Question | Specification answer |
|---|---|
| Will the callback run? | Not guaranteed |
| When will it run? | Unspecified, possibly much later |
| Will it run at program exit? | Usually not |
| Are objects collected in a predictable order? | No |
Exercise
Your callback receives { target: obj, label: 'x' } as its held value. Why is obj never finalized?
Show answer
The registry holds the held value strongly, and the held value references obj. That keeps obj reachable, so it is never collected and the callback never runs.