Sub topic 15
When to Use Explicit Cleanup Instead
This chapter assumes you have read the earlier chapters on FinalizationRegistry, unregister tokens, and the timing guarantees the engine does not make. It also assumes you are comfortable with try/finally and classes.
Explicit cleanup should be your main strategy. Finalization is only a fallback. This chapter explains why and shows the tools to use instead.
Why Finalization Cannot Be the Primary Plan
The specification does not promise that a cleanup callback will ever run. If it does run, it may be long after the object became unreachable. A program can also exit before any callbacks run. That rules finalization out for anything that must happen:
- Closing file descriptors, sockets, or database connections before a limit is reached.
- Flushing buffered writes to disk.
- Releasing locks that other code is waiting on.
- Removing event listeners so that handlers stop firing.
When the cleanup affects correctness, write code that runs it at a known point.
The Explicit Toolbox
Close in `finally`
The simplest pattern is an owner that calls close() when it is done, with the call inside finally so that errors do not skip it.
class Connection {
constructor(name) {
this.name = name;
this.open = true;
console.log(`opened ${name}`);
}
query(sql) {
if (!this.open) throw new Error('connection closed');
return `result of ${sql}`;
}
close() {
if (!this.open) return; // safe to call twice
this.open = false;
console.log(`closed ${this.name}`);
}
}
function run() {
const conn = new Connection('db');
try {
console.log(conn.query('SELECT 1'));
} finally {
conn.close();
}
}
run();Make close() idempotent, meaning a second call does nothing. Then callers and fallback paths can both call it without double-releasing anything.
`using` and `Symbol.dispose`
Explicit Resource Management adds using declarations. When the enclosing block exits, normally or by throwing, the engine calls the object's [Symbol.dispose]() method. It runs Node.js 24+ and recent Chromium-based browsers. Check your target runtime before relying on it.
class TempLock {
constructor(id) {
this.id = id;
console.log(`acquired ${id}`);
}
[Symbol.dispose]() {
console.log(`released ${this.id}`);
}
}
{
using lock = new TempLock('job-1');
console.log('doing work');
} // "released job-1" prints here, deterministicallyFor asynchronous release, implement [Symbol.asyncDispose]() and use await using.
Cancellation with `AbortController`
To remove listeners or stop pending work, pass an AbortSignal and abort it when the owner is finished:
const controller = new AbortController();
globalThis.addEventListener?.('resize', () => {}, { signal: controller.signal });
controller.abort(); // listener removed now, not "eventually"Combining Both
The pattern from the safety-net chapter still applies. Explicit close() does the real work and calls registry.unregister(this). The finalizer only catches leaks and logs a warning. Treat that warning as a bug report: some code path forgot to clean up.
Decision Guide
| Situation | Use |
|---|---|
| File, socket, or connection handles | `close()` in `finally`, or `using` |
| Locks or transactions | `using` with `Symbol.dispose` |
| Event listeners and timers | `AbortController` or explicit removal |
| Cached derived data that can be recomputed | `WeakRef` cache |
| Detecting forgotten `close()` calls | `FinalizationRegistry` that logs a warning |
Exercise
A logger buffers lines in memory and writes them to a file in a FinalizationRegistry callback when the logger object is collected. Why is this unsafe, and what should replace it?
Show answer
The callback may run late or never. If the process exits first, the buffered lines are lost. Give the logger an idempotent flush-and-close method, implemented as [Symbol.dispose] or [Symbol.asyncDispose], and call it with using, await using, or try/finally. A finalizer may remain only to warn that close was skipped.
Exercise
Why should close() be idempotent when it is paired with a finalization fallback?
Show answer
Both the explicit path and the fallback path, or several callers, may try to release the resource. If close() does nothing after the first call, the resource is never released twice and repeated calls do not throw.