javascript / expert
Snippet
Memory Management with FinalizationRegistry
WeakRefs allow referencing an object without preventing its garbage collection (GC). Combined with FinalizationRegistry, developers can execute cleanup logic or manage external resources (like file handles) precisely when the JavaScript object is reclaimed by the engine.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const registry = new FinalizationRegistry((key) => {console.log(`Resource ${key} was garbage collected`);});let cacheObject = { data: 'heavy_payload' };const weakRef = new WeakRef(cacheObject);registry.register(cacheObject, 'session_cache_01');// Simulate object losscacheObject = null;
nodejs
Breakdown
1
new WeakRef(cacheObject);
Creates a reference that doesn't keep the object alive for the GC.
2
registry.register(cacheObject, 'session_cache_01');
Links the object to a callback triggered upon its destruction.