javascript / expert
Snippet
WeakRef Resource Lifecycle Tracking and Garbage Collection Cleanup
This snippet demonstrates advanced memory management in Node.js using FinalizationRegistry and WeakRef. FinalizationRegistry allows registering a cleanup callback triggered asynchronously after an object reference is reclaimed by V8's garbage collector, while WeakRef maintains a weak reference to an object without preventing its collection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { FinalizationRegistry } from 'node:v8';class ManagedResource {#registry = new FinalizationRegistry((heldValue) => {console.log(`Resource ${heldValue.id} was garbage collected. Cleaning up native handle ${heldValue.handle}`);});register(target, metadata) {this.#registry.register(target, metadata, target);}unregister(target) {this.#registry.unregister(target);}}const manager = new ManagedResource();let session = { id: 'sess_102', handle: 0xDEADBEEF };manager.register(session, { id: session.id, handle: session.handle });const weakSession = new WeakRef(session);session = null;
nodejs
Breakdown
1
import { FinalizationRegistry } from 'node:v8';
Imports the V8 engine module's FinalizationRegistry utility for tracking memory reclamation.
2
#registry = new FinalizationRegistry((heldValue) => {
Instantiates a private class field holding a registry callback that receives non-collectable metadata when the target object is finalized.
3
this.#registry.register(target, metadata, target);
Registers the target object with custom cleanup metadata and uses the target object itself as the unregister token.
4
const weakSession = new WeakRef(session);
Creates a WeakRef to monitor object availability without creating a strong memory reference.
5
session = null;
Clears the strong reference to allow V8's garbage collector to reclaim the session object.