Sub topic 15
When to Use Explicit Cleanup Instead
The earlier chapters showed what WeakRef and FinalizationRegistry can do. This chapter covers the opposite question: when you should not rely on them. It assumes you know JavaScript classes, closures, try/finally, and promises, and that you have read the earlier chapters on finalization timing and resource cleanup.
In short, the program itself should release anything that matters. Garbage collection decides when memory is reclaimed. It was never meant to decide when your file is closed, your lock is released, or your buffered data is written.
Why Finalization Cannot Be the Primary Strategy
The specification makes almost no promises about cleanup callbacks. A callback may run late or never, for example when the page is closed or the process exits. Engines may also batch callbacks or skip them under memory pressure. Garbage collection is driven by memory pressure, so a program that holds very little memory may never trigger a collection, even while it runs out of file descriptors or database connections.
That mismatch drives everything else in this chapter. Memory and external resources run out on different schedules.
| Resource | What runs out | Does GC notice? |
|---|---|---|
| Plain objects, arrays | Heap memory | Yes, this is its job |
| File descriptors | OS per-process limit (often 1024) | No |
| Database connections | Pool size (often 10 to 20) | No |
| Locks, mutexes | Availability for other code | No |
| Buffered writes | Durability of data | No |
| WebAssembly linear memory | Wasm heap, invisible to the JS GC | Only indirectly |
When the scarce thing is not JavaScript heap memory, the collector has no reason to run. A finalizer tied to that collector cannot protect the resource.
The Explicit Cleanup Toolbox
Explicit cleanup means the code that acquires a resource also states, in its own control flow, where the resource is released. JavaScript has several ways to do this.
close() or dispose() with try/finally
The oldest pattern still works everywhere. Give the resource a release method and call it in a finally block so it runs even when an exception is thrown.
class TempConnection {
constructor(name) {
this.name = name;
this.open = true;
console.log(`open ${name}`);
}
query(sql) {
if (!this.open) throw new Error('connection is closed');
return `result of ${sql}`;
}
close() {
if (!this.open) return; // idempotent: a second close() is harmless
this.open = false;
console.log(`close ${this.name}`);
}
}
const conn = new TempConnection('db');
try {
console.log(conn.query('SELECT 1'));
} finally {
conn.close();
}Make close() idempotent, meaning a second call does nothing. Real code often reaches cleanup by more than one path, and a second call should not throw or free something twice.
using and Symbol.dispose
Explicit Resource Management adds using declarations. An object with a [Symbol.dispose]() method is disposed automatically when the block that declared it exits, whether the block finishes normally or throws. Resources are disposed in reverse order of declaration. The syntax is available in Node.js 24+ and Chromium-based browsers from version 134. Check your target runtimes before you rely on it.
class Lock {
constructor(name) {
this.name = name;
console.log(`acquire ${name}`);
}
[Symbol.dispose]() {
console.log(`release ${this.name}`);
}
}
function work() {
using a = new Lock('a');
using b = new Lock('b');
console.log('working');
} // prints "release b", then "release a"
work();For asynchronous release, such as flushing a stream, implement [Symbol.asyncDispose]() and declare the variable with await using inside an async function. DisposableStack and AsyncDisposableStack collect several resources whose number is only known at runtime and dispose all of them together.
function openAll(names) {
using stack = new DisposableStack();
const locks = names.map((n) => stack.use(new Lock(n)));
console.log(`holding ${locks.length} locks`);
// To hand ownership to the caller instead, return stack.move()
} // all locks released here, in reverse order
openAll(['x', 'y', 'z']);If more than one disposer throws, the runtime wraps the errors in a SuppressedError, so no failure is silently lost. A finally block written by hand will often drop the first error when a second one is thrown.
AbortController for listeners and pending work
Event listeners, timers, and in-flight requests also count as resources. If you forget to remove them, they keep closures, and everything those closures capture, reachable. An AbortSignal lets a single call tear all of them down.
const controller = new AbortController();
const target = new EventTarget();
target.addEventListener('ping', () => console.log('ping'), {
signal: controller.signal,
});
target.dispatchEvent(new Event('ping')); // prints "ping"
controller.abort(); // removes the listener
target.dispatchEvent(new Event('ping')); // prints nothingThe same signal can be passed to fetch() and many Node.js APIs. A component's "unmount" step then reduces to one abort() call.
Combining Both: Explicit First, Finalization as a Warning
The safety-net pattern from the earlier chapter stays useful as long as it plays a supporting role. Explicit disposal is the real cleanup path. It also unregisters the finalizer. The finalizer then runs only for objects someone forgot to dispose, so its main job is to report that bug.
const leakDetector = new FinalizationRegistry((label) => {
console.warn(`Leak: ${label} was never disposed`);
});
class Session {
#closed = false;
constructor(id) {
this.id = id;
// held value is a string, token is the Session itself
leakDetector.register(this, `session ${id}`, this);
}
[Symbol.dispose]() {
if (this.#closed) return;
this.#closed = true;
leakDetector.unregister(this);
console.log(`session ${this.id} closed`);
}
}
function handleRequest() {
using s = new Session(1); // disposed explicitly, finalizer cancelled
new Session(2); // forgotten: may eventually log a leak warning
}
handleRequest();Treat the warning as a diagnostic. If it fires in testing, fix the missing using or close(). Do not take it as proof that cleanup is handled.
Decision Criteria
Use explicit cleanup when any of the following is true:
- The resource is limited outside the JS heap: descriptors, sockets, pool slots, GPU buffers, Wasm memory.
- Release has side effects other code can see, such as flushing writes, sending a "goodbye" message, or releasing a lock.
- Order matters, for example closing a transaction before its connection.
- Correctness or tests depend on the release happening at a known point.
Finalization or weak references are reasonable when all of these hold:
- Only memory is at stake, and losing the value means recomputing it, not losing data.
- The program stays correct if the callback never runs.
- You use it for diagnostics, metrics, or opportunistic trimming of side tables.
Common Errors
- Flushing data in a finalizer. If the process exits first, the data is lost without any error. Flush inside
close()or[Symbol.asyncDispose](). - Forgetting to unregister on explicit close. The finalizer later runs against a handle that is already closed. Depending on the API, that means a double-free, an error, or a misleading leak warning.
- Non-idempotent dispose.
usingcombined with a manualclose()call, or two code paths that both clean up, will call it twice. - Calling
close()outsidefinally. An exception thrown before the call skips it. Usefinallyorusing. - Assuming
usingworks everywhere. Older runtimes throw aSyntaxErrorwhen they parse the file. Transpile, or fall back totry/finally. - Treating "the finalizer fired in my test" as a guarantee. A test that forces GC with
--expose-gcsays nothing about production timing.
Exercises
Exercise
A logging class buffers lines in memory and writes them to a file when the buffer fills. A teammate proposes a FinalizationRegistry that writes any remaining buffered lines when the logger is collected. What goes wrong, and what should be done instead?
Show answer
The callback may run late or never, for example when the process exits, so the last lines can be lost without any error. The logger should expose an async dispose method, [Symbol.asyncDispose]() or close(), that flushes and closes the file, and callers should use await using or try/finally. A FinalizationRegistry could still log a warning that the logger was never closed. It must not be the code that does the flush.
Exercise
In the Session example, what happens if [Symbol.dispose]() omits the leakDetector.unregister(this) call, and why does the token argument matter?
Show answer
Every session, including correctly disposed ones, could later produce a "Leak" warning, which makes the detector useless. Passing this as the unregister token is what lets dispose cancel that specific registration. Without a token, unregister() has nothing to match against.
Exercise
You need to hold three database connections whose count is only known at runtime, and release all of them even if opening the third one throws. Which tool fits best?
Show answer
A DisposableStack, or an AsyncDisposableStack if release is asynchronous, declared with using. Each connection is added with stack.use() as soon as it opens. If a later open throws, leaving the block disposes the connections already added, in reverse order, and combines multiple disposal errors into a SuppressedError.