A FinalizationRegistry
object lets you request a callback when a value is garbage-collected.
A FinalizationRegistry
object lets you request a callback when a value is garbage-collected.
FinalizationRegistry
provides a way to request that a cleanup callback get called at some point when a value registered with the registry has been reclaimed (garbage-collected). (Cleanup callbacks are sometimes called finalizers.)
Note: Cleanup callbacks should not be used for essential program logic. See Notes on cleanup callbacks for details.
You create the registry passing in the callback:
const registry = new FinalizationRegistry((heldValue) => { // … });
Then you register any value you want a cleanup callback for by calling the register
method, passing in the value and a held value for it:
registry.register(target, "some value");
The registry does not keep a strong reference to the value, as that would defeat the purpose (if the registry held it strongly, the value would never be reclaimed). In JavaScript, objects and non-registered symbols are garbage collectable, so they can be registered in a FinalizationRegistry
object as the target or the token.
If target
is reclaimed, your cleanup callback may be called at some point with the held value you provided for it ("some value"
in the above). The held value can be any value you like: a primitive or an object, even undefined
. If the held value is an object, the registry keeps a strong reference to it (so it can pass it to your cleanup callback later).
If you might want to unregister a registered target value later, you pass a third value, which is the unregistration token you'll use later when calling the registry's unregister
function to unregister the value. The registry only keeps a weak reference to the unregister token.
It's common to use the target value itself as the unregister token, which is just fine:
registry.register(target, "some value", target); // … // some time later, if you don't care about `target` anymore, unregister it registry.unregister(target);
It doesn't have to be the same value, though; it can be a different one:
registry.register(target, "some value", token); // … // some time later registry.unregister(token);
Correct use of FinalizationRegistry
takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.
Here are some specific points included by the authors in the proposal that introduced FinalizationRegistry
:
Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:
- One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
- Garbage collection work can be split up over time using incremental and concurrent techniques.
- Various runtime heuristics can be used to balance memory usage, responsiveness.
- The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
- Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
- Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
FinalizationRegistry
instance itself is no longer reachable by JavaScript code.WeakRef
is also in a FinalizationRegistry
, the WeakRef
's target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls deref
on a WeakRef
for the object, it will receive undefined
.FinalizationRegistry()
Creates a new FinalizationRegistry
object.
These properties are defined on FinalizationRegistry.prototype
and shared by all FinalizationRegistry
instances.
FinalizationRegistry.prototype.constructor
The constructor function that created the instance object. For FinalizationRegistry
instances, the initial value is the FinalizationRegistry
constructor.
FinalizationRegistry.prototype[@@toStringTag]
The initial value of the @@toStringTag
property is the string "FinalizationRegistry"
. This property is used in Object.prototype.toString()
.
FinalizationRegistry.prototype.register()
Registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected.
FinalizationRegistry.prototype.unregister()
Unregisters an object from the registry.
You create the registry passing in the callback:
const registry = new FinalizationRegistry((heldValue) => { // … });
Then you register any objects you want a cleanup callback for by calling the register
method, passing in the object and a held value for it:
registry.register(theObject, "some value");
No matter how much pressure you put on the garbage collector, the cleanup callback will never be called synchronously. The object may be reclaimed synchronously, but the callback will always be called sometime after the current job finishes:
let counter = 0; const registry = new FinalizationRegistry(() => { console.log(`Array gets garbage collected at ${counter}`); }); registry.register(["foo"]); (function allocateMemory() { // Allocate 50000 functions — a lot of memory! Array.from({ length: 50000 }, () => () => {}); if (counter > 5000) return; counter++; allocateMemory(); })(); console.log("Main job ends"); // Logs: // Main job ends // Array gets garbage collected at 5001
However, if you allow a little break between each allocation, the callback may be called sooner:
let arrayCollected = false; let counter = 0; const registry = new FinalizationRegistry(() => { console.log(`Array gets garbage collected at ${counter}`); arrayCollected = true; }); registry.register(["foo"]); (function allocateMemory() { // Allocate 50000 functions — a lot of memory! Array.from({ length: 50000 }, () => () => {}); if (counter > 5000 || arrayCollected) return; counter++; // Use setTimeout to make each allocateMemory a different job setTimeout(allocateMemory); })(); console.log("Main job ends");
There's no guarantee that the callback will be called sooner or if it will be called at all, but there's a possibility that the logged message has a counter value smaller than 5000.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
FinalizationRegistry |
84 | 84 | 79 | 70 | 14.1 | 84 | 79 | 60 | 14.5 | 14.0 | 84 | 1.0 | 14.6.0 | |
FinalizationRegistry |
84 | 84 | 79 | 70 | 14.1 | 84 | 79 | 60 | 14.5 | 14.0 | 84 | 1.0 | 14.6.0 | |
register |
84 | 84 | 79 | 70 | 14.1 | 84 | 79 | 60 | 14.5 | 14.0 | 84 | 1.0 | 14.6.0 | |
symbol_as_target |
108 | 108 | No | 94 | 16.4 | 108 | No | 73 | 16.4 | 21.0 | 108 | No | No | |
unregister |
84 | 84 | 79 | 70 | 14.1 | 84 | 79 | 60 | 14.5 | 14.0 | 84 | 1.0 | 14.6.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry