Sub topic 12
Finalization as a Safety Net for External Resources
This chapter assumes you already know how FinalizationRegistry, held values, and unregister tokens work, and that the engine gives no guarantee about when or whether cleanup callbacks run. Here we put those pieces together into one practical pattern: a backup cleanup path for resources that live outside the JavaScript heap.
The problem: resources the GC cannot see
Some objects only point at something external, such as a file descriptor, a socket, a database connection, or a native buffer. The garbage collector frees the small JavaScript wrapper object. It knows nothing about the operating system handle behind it. If a caller forgets to call close(), that handle leaks until the process exits.
Finalization cannot fix forgetful callers reliably. It can still catch some of their mistakes, and it can log a warning so the bug gets noticed and fixed.
The pattern
The design follows three rules:
close()is the primary path, and callers are expected to use it.- The wrapper registers itself with a registry. The held value is the inner handle, and the unregister token is the wrapper.
close()unregisters the wrapper so the fallback never runs twice.
class FakeFileHandle {
constructor(fd) { this.fd = fd; this.closed = false; }
close() {
if (this.closed) return;
this.closed = true;
console.log(`fd ${this.fd} closed`);
}
}
const registry = new FinalizationRegistry((fileHandle) => {
console.warn(`Handle fd ${fileHandle.fd} 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();
}
}
// Correct use: explicit close, so the fallback is cancelled.
const good = new Wrapper(new FakeFileHandle(3));
good.close();
// Forgotten close: the fallback may run at some later time, or never.
(function () {
new Wrapper(new FakeFileHandle(4));
})();Run this in Node.js and you will see fd 3 closed straight away. The warning for fd 4 may show up later, or it may never show up before the process exits. Both results are correct behavior.
Why each choice matters
| Choice | Reason |
|---|---|
| Held value is `fileHandle`, not `this` | The registry holds held values strongly. Holding the wrapper would keep it alive forever, and `register()` throws if the held value is the target itself. |
| Token is `this` | Tokens are held weakly, so using the wrapper as its own token costs nothing and makes `unregister(this)` easy. |
| `close()` on the handle is idempotent | A double close stays harmless even if your code has a race or a bug. |
| Callback logs a warning | A finalizer that runs points to a bug in the caller. The log makes that bug visible. |
Limits of the safety net
- The callback might never run, for example on process exit, page unload, or when the engine just doesn't collect. Never use finalization for anything that must happen, such as flushing writes or committing a transaction.
- Callbacks run late, so a busy program can run out of handles before the GC catches up.
- Node.js itself moved away from relying on this. Closing an
fs.FileHandleon garbage collection is deprecated (DEP0137), and Node asks code to close handles explicitly.
Treat the fallback as a way to catch mistakes, with a log line attached. It does not replace a cleanup strategy.
Exercise
A teammate changes the registration to registry.register(this, this) so the callback can call wrapper.close(). What goes wrong?
Show answer
The held value is the target itself. register() throws a TypeError, because a strongly held value equal to the target would keep it alive forever. Even an indirect version, where the held value references the wrapper, would stop the wrapper from ever being collected. Pass the inner handle as the held value instead.
Exercise
Why does Wrapper.close() call registry.unregister(this) before closing the handle?
Show answer
It cancels the finalization fallback. The callback then never fires for a resource that was already released, which avoids a misleading warning and a second close attempt.