Best-effort cache cleanup
Release or remove non-critical cached data after its associated object is reclaimed.
JavaScript · Class
FinalizationRegistry lets you request a cleanup callback after a registered value is garbage-collected. Callback execution and timing are controlled by the JavaScript engine and are not guaranteed.
Create a registry with a cleanup callback, then register an object together with a separate held value. If the object becomes garbage-collectable, the engine may later invoke the callback with that held value; callback timing and execution are not guaranteed.
new FinalizationRegistry(callbackFn)| Name | Type | Description |
|---|---|---|
callbackFn | function | Function called when a registered target is garbage-collected; its return value is ignored. |
target | object or non-registered symbol | Value to register for possible cleanup notification. |
heldValue | any | Value passed to the cleanup callback; it cannot be target. |
unregisterToken | object or non-registered symbol | Optional object or non-registered symbol used later to unregister the registration. |
The constructor creates a FinalizationRegistry object; register() and unregister() return undefined.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Clean up: ${heldValue}`);
});
let resource = { id: 42 };
registry.register(resource, "resource 42");
resource = null;
// The callback may run later, or not at all.Registers an object with a cleanup callback; the callback receives the associated held value if the object is reclaimed.
Release or remove non-critical cached data after its associated object is reclaimed.
Perform fallback cleanup for resources whose handles can no longer be accessed after collection.
Remove registrations when an object is explicitly disposed before garbage collection.
It associates a cleanup callback with registered targets. After a target is garbage-collected, the engine may call the callback with the registration's held value, but neither collection nor callback timing is guaranteed.
Follow-up: Why should finalization not release a critical resource? Because the callback may never run, so critical cleanup must have an explicit deterministic path.
Construct it with a callback, then call register(target, heldValue). The callback receives heldValue rather than the target, which is no longer safely available after collection.
Follow-up: How can a registration be removed? Supply an object or non-registered symbol as unregisterToken, then pass that same token to unregister().
The third register() argument is an optional unregistration token. If present and valid, it can later identify the registration for unregister(); if omitted, the target cannot be unregistered.
Follow-up: What restrictions apply to the token? It must be an object or a non-registered symbol when it is not undefined.
FinalizationRegistry.prototype.register()FinalizationRegistry.prototype.unregister()WeakRefWeakMap