Sub topic 9
Cancelling Registrations with Unregister Tokens
A cleanup callback is meant as a fallback. Suppose your code has already released a resource on purpose. When the object is later collected, the callback should not run a second time. The third argument to register(), called the unregister token, lets you cancel a registration before the callback fires.
This chapter assumes you know how FinalizationRegistry and register() work. It also assumes you know what a held value is and that the callback receives it. You should be comfortable with closures and classes too.
The Full Signature of register()
register() takes up to three arguments:
registry.register(target, heldValue, unregisterToken);| Argument | Required | How the registry holds it | Purpose |
|---|---|---|---|
| `target` | Yes | Weakly | The object whose collection you want to hear about |
| `heldValue` | No | Strongly | The data passed to the cleanup callback |
| `unregisterToken` | No | Weakly | A key you can later pass to `unregister()` |
If you leave out the token, nothing can cancel that registration. The callback may run once the target is collected, and no code can stop it. So pass a token whenever your code might clean up the resource on its own.
unregister() and Its Return Value
unregister(token) removes every registration made with that token, then returns a boolean. It returns true if it removed at least one registration and false if it found none.
const registry = new FinalizationRegistry((held) => {
console.log(`cleanup for ${held}`);
});
const target = {};
const token = {};
registry.register(target, 'item-1', token);
console.log(registry.unregister(token)); // true: one registration removed
console.log(registry.unregister(token)); // false: nothing left to removeCalling unregister() again with the same token is safe and just returns false. Because of this, a close() method can call unregister() every time without first checking whether it has already been called.
What Can Be a Token
The token follows the same rule as a WeakRef target. It must be something that can be held weakly: an object, or a symbol that was not created with Symbol.for(). Anything else causes a TypeError, both in register() and in unregister().
const registry = new FinalizationRegistry(() => {});
const target = {};
try {
registry.register(target, 'x', 'not-an-object');
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
registry.unregister(42);
} catch (err) {
console.log(err instanceof TypeError); // true
}
registry.register(target, 'x', Symbol('local')); // allowed: unregistered symbol
registry.register(target, 'y', undefined); // allowed: means "no token"Explicitly passing undefined counts the same as leaving the argument out. A string ID such as 'resource-42' cannot be a token, even though it would make a natural lookup key. If you want to cancel by ID, keep a Map from IDs to token objects.
The Token Is Held Weakly
The registry does not keep the token alive. This matters most in the common case where the token is the target itself:
registry.register(obj, someHeldValue, obj);This would be a bug for the held value, because the registry holds held values strongly, so obj could never be collected. (For that reason, passing the target as the held value throws.) The token is held weakly, so using the target as its own token adds no strong reference.
The weak hold has a consequence. If the token is collected, the registration stays in place, but nobody can unregister it any more. The callback can still run when the target is collected. In practice this rarely causes trouble, because the code that wants to call unregister() must hold the token anyway, and holding it keeps it alive.
The Canonical Pattern: The Wrapper Is Its Own Token
The most common use registers a wrapper object, passes the inner handle as the held value, and uses the wrapper as the token. Explicit close() then cancels the fallback:
const registry = new FinalizationRegistry((handle) => {
console.warn(`Handle ${handle.id} leaked; closing it now`);
handle.close();
});
class Connection {
constructor(id) {
this.handle = {
id,
closed: false,
close() {
this.closed = true;
console.log(`handle ${this.id} closed`);
},
};
registry.register(this, this.handle, this);
}
close() {
if (this.handle.closed) return;
registry.unregister(this);
this.handle.close();
}
}
const conn = new Connection(7);
conn.close(); // "handle 7 closed"; the leak warning can never fire for conn
conn.close(); // no output: already closedHere is how the pieces fit:
- The registry holds
this.handlestrongly as the held value. That is fine, because the handle does not point back to theConnection. thisis the target and also the token. Both are held weakly, so theConnectioncan still be collected.close()callsunregister(this)before it releases the handle. After that, no callback can close the handle a second time.
Cancelling Between Collection and Callback
The diagram shows that a registration can sit in a pending state. The target has been collected, but the engine has not yet scheduled the callback. If unregister() is called during that window, the registration is removed and the callback does not run for it.
When the token is the target, you cannot reach that window, because the token was collected along with the target and you no longer have anything to pass to unregister(). When the token is a separate object, you can. For example, an owner might keep a token after the tracked object is gone and use it to cancel cleanup it no longer needs. Write callbacks so they are harmless whether or not they run.
One Token, Many Registrations
A token can be shared across any number of registrations, and one unregister() call removes all of them. This is useful when several objects belong to one owner:
const registry = new FinalizationRegistry((label) => {
console.log(`collected ${label}`);
});
class Session {
constructor() {
this.token = {};
this.parts = [];
}
track(part, label) {
this.parts.push(part);
registry.register(part, label, this.token);
}
end() {
const removed = registry.unregister(this.token);
this.parts.length = 0;
console.log(`session ended, registrations removed: ${removed}`);
}
}
const session = new Session();
session.track({ kind: 'buffer' }, 'buffer-1');
session.track({ kind: 'buffer' }, 'buffer-2');
session.end(); // "session ended, registrations removed: true"The boolean only tells you whether at least one registration was removed. It does not say how many. If you need a count, track it yourself.
The reverse also works. You can register the same target more than once with different tokens, then cancel each registration on its own.
Edge Cases and Mistakes
| Situation | Behavior |
|---|---|
| No token passed | The registration cannot be cancelled |
| Token is a string, number, or `Symbol.for()` symbol | `TypeError` |
| `unregister()` called twice | First call returns `true`, second returns `false` |
| Token never used in `register()` | Returns `false`, no error |
| Token used on a different registry | Returns `false`; tokens belong to one registry |
| Token is the held value | Allowed, but the strong held value keeps the token alive |
| Token collected before `unregister()` | The registration stays and the callback may still run |
There are a few other mistakes to watch for:
- Releasing the resource before unregistering. If
close()frees the handle and then throws before callingunregister(), the fallback can run later on a handle that is already closed. Callunregister()first, or make the handle'sclose()idempotent so a second call does nothing. - Re-registering on reuse. If an object pool recycles a wrapper, unregister it when it goes back to the pool and register it again when it is handed out. If you skip this, you end up with duplicate registrations and duplicate callbacks.
- Relying on unregistration for correctness.
unregister()only stops a callback. It does not release anything. The explicit release inclose()is what does the real work.
Exercise
A class calls registry.register(this, this, this) in its constructor. What happens, and how should the call be fixed?
Show answer
register() throws a TypeError, because the held value is the same object as the target. The registry would hold it strongly, so the target could never be collected. Pass the inner resource or a plain identifier as the held value instead, for example registry.register(this, this.handle, this), and keep this as the weakly held target and token.
Exercise
Code registers three objects with the shared token ownerToken. It then calls registry.unregister(ownerToken) twice. What does each call return, and how many callbacks can still run for those three objects?
Show answer
The first call returns true, because it removed all three registrations. The second returns false. No callbacks can run for those objects, because all three registrations are gone.
Exercise
Why can't you write registry.register(obj, 'id-9', 'id-9') so you can later cancel by string, and what is a working alternative?
Show answer
Tokens must be values that can be held weakly, meaning objects or non-registered symbols. A string throws a TypeError. Instead, create a token object for each ID, store it in a Map such as tokens.set('id-9', tokenObj), pass tokenObj to register(), and later call registry.unregister(tokens.get('id-9')).