Sub topic 3
Building a Weak-Value Cache
This chapter assumes you already know WeakRef, deref(), FinalizationRegistry, held values, and unregister tokens from the earlier chapters. It uses those pieces to build two patterns, then explains where they fail.
The Weak-Value Cache
A WeakMap holds its keys weakly, but this cache needs the opposite. Its keys are strings, and its values should be free to be collected. The solution is a Map from each key to a WeakRef of its value, plus a registry that removes entries whose values have been collected.
const cache = new Map();
const registry = new FinalizationRegistry((key) => {
const ref = cache.get(key);
if (ref !== undefined && ref.deref() === undefined) {
cache.delete(key);
}
});
function getCached(key, compute) {
const cached = cache.get(key)?.deref();
if (cached !== undefined) return cached;
const value = compute(key);
cache.set(key, new WeakRef(value));
registry.register(value, key);
return value;
}
const report = getCached('q1', (k) => ({ key: k, rows: new Array(1e5) }));
console.log(report.key); // q1The callback checks the entry before it deletes anything. The old value can be collected after the same key has been filled with a new value. Without the check, the late callback would delete the new, live entry.
Finalization as a Safety Net
A wrapper can register itself so that a handle the caller forgot to close still gets closed eventually:
const registry = new FinalizationRegistry((fileHandle) => {
console.warn('Handle was not closed explicitly; closing now');
fileHandle.close();
});
class Wrapper {
constructor(fileHandle) {
this.fileHandle = fileHandle;
registry.register(this, fileHandle, this);
}
close() {
registry.unregister(this);
this.fileHandle.close();
}
}The held value is the inner handle and the unregister token is the wrapper. Calling close() cancels the fallback, so the handle is never closed twice.
Pitfalls
| Mistake | Effect |
|---|---|
| Held value references the target | Target never collected (`register(obj, obj)` throws) |
| Callback closure captures the target | Target kept alive by the registry |
| Relying on the callback for correctness | Callback may run late or never |
| Deleting cache entries without re-checking | Live entries removed |
Observing GC
In Node.js, run with node --expose-gc and call globalThis.gc() for experiments. Chrome DevTools has a "Collect garbage" button in the Memory panel. Neither one guarantees when callbacks run, so tests should never assert on finalization timing.
Prefer Explicit Cleanup
Always release resources such as files, sockets, and locks with close(), try...finally, or using where it is supported. Treat finalization as a diagnostic backup.
Exercise
Why does the cache's cleanup callback call deref() before deleting the key?
Show answer
The key may have been refilled with a new value after the old value was collected. The check stops a late callback from deleting the live entry.
Exercise
In the Wrapper class, why is the inner fileHandle the held value instead of the wrapper itself?
Show answer
A held value is held strongly. Using the wrapper (the target) would keep it alive forever, and register() throws a TypeError when the held value is the target.