javascript / expert
Snippet
Lifecycle Management with FinalizationRegistry
The FinalizationRegistry API allows you to request a callback when an object is garbage collected. This is crucial for managing low-level resources like file descriptors or external cache connections that aren't automatically cleaned up by the JS engine.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
const registry = new FinalizationRegistry((heldValue) => {console.log(`Resource ${heldValue} was garbage collected`);});function createHeavyResource(id) {const resource = { id, data: new BigInt64Array(1024) };registry.register(resource, id);return resource;}let temp = createHeavyResource('connection_01');temp = null; // Eligible for GC
nextjs
Breakdown
1
new FinalizationRegistry((heldValue) => { ... });
Creates a registry that executes a callback with the associated value after GC.
2
registry.register(resource, id);
Registers an object to be tracked, mapping it to a specific metadata value (id).
3
temp = null;
Removes the only reference to the object, making it eligible for garbage collection.