JavaScript · Question 95
Why should WeakRef and FinalizationRegistry not be used for deterministic resource cleanup?
Direct answer
Garbage collection timing is intentionally non-deterministic and the specification does not guarantee that an unreachable target will be collected promptly—or at all—so WeakRef and finalization callbacks cannot provide reliable timing for releasing critical resources.
A WeakRef can allow code to observe a target without creating an ordinary strong reference that necessarily keeps it live. FinalizationRegistry can register cleanup-related callbacks associated with targets. These features are deliberately constrained because garbage collection is an implementation concern with substantial optimization freedom.
The engine may keep an otherwise unreachable object for an arbitrary period, and cleanup callbacks are not guaranteed to run at a predictable moment. Therefore closing a file-like resource, releasing a lock, committing data, or performing any correctness-critical action should use explicit lifecycle code rather than waiting for GC.
- Good use cases are cache-like or auxiliary behavior where cleanup is opportunistic.
- Do not write logic whose correctness depends on a finalizer running before process/page termination.
- Avoid repeatedly calling
deref()and assuming a weak target’s lifetime is stable across asynchronous boundaries.