Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Keeping Cleanup Deterministic

Keeping Cleanup Deterministic

In this lesson, you make sure the match-log processor closes what it opens. For each match, it opens a replay log that has to be closed once the processor is done with it. Here, closing a log prints a line, a stand-in for a real file.

In Python, weakref.finalize() registers a callback that runs when an object is collected: here, it prints closed M1. Then the script deletes its only reference to the log:

Language: Python
import weakref

class MatchLog:
    def __init__(self, match):
        self.match = match

log = MatchLog("M1")
weakref.finalize(log, print, "closed", "M1")
del log
print("dropped the log")

CPython counts references, so the count reaches zero at del, and the log is closed before the script goes on:

Language: Program Output
closed M1
dropped the log

JavaScript’s closest counterpart is a FinalizationRegistry, which takes a cleanup callback, here closeLog(). Its register() method watches the log, and the second argument, "M1", is the held value the callback receives. Setting log to null clears the only reference, as del did:

Language: JavaScript
const closeLog = (match) => console.log("closed", match);
const registry = new FinalizationRegistry(closeLog);

let log = { match: "M1" };
registry.register(log, "M1");
log = null;
console.log("dropped the log");

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 In this lesson, you’ll make sure the match-log processor closes what it opens. For each match, it opens a replay log that has to be closed once the processor is done with it.

00:11 In Python, weakref.finalize() registers a callback that runs when an object is collected: here, it prints closed M1. Then the script deletes its only reference to the log.

00:24 CPython counts references, so the count reaches zero at del, and the output shows the log closed before the script goes on.

00:34 JavaScript’s closest counterpart is a FinalizationRegistry, which takes a cleanup callback, here closeLog(). Its register() method watches the log, and the second argument, M1, is the held value the callback receives.

00:49 Setting log to null clears the only reference, as del did. Python printed closed M1 first. When does JavaScript print it?

00:59 Your turn: pause the video and predict.

01:08 Only the script’s own line appears. On this machine, closed M1 never printed, in any run.

01:18 Why? As with the match history, clearing a reference collects nothing. JavaScript promises no reference counting and no collection time. V8, the engine under Node, traces what’s reachable when it decides to, like CPython’s cycle collector, but for every object.

01:36 This script ended first, so the callback never ran. For testing, node --expose-gc adds a gc() function that asks for a collection.

01:47 With it, closed M1 appears, but only after the script’s last line. Unlike Python’s gc.collect(), gc() doesn’t run the callback: JavaScript queues it until your running code finishes.

02:02 So a finalizer is advisory: it may run late, in any order, or never. Python’s prompt close came from reference counting; a log in a cycle would wait there too, and Python’s reference says to close resources explicitly.

02:19 The processor also keeps notes on players it doesn’t own. A WeakRef holds an object without keeping it alive, like Python’s weakref.ref().

02:29 deref() returns the object, or undefined once it’s collected. In Python, after del, the weak reference already returns None.

02:39 In JavaScript, the same steps find the player, even with gc(): a WeakRef made or read in running code keeps its target until that code finishes.

02:50 Code that runs later, like a timer callback, can get undefined: one did here, with gc(). Each deref() call asks again, so read it once into a constant and check it before use.

03:02 That constant is a strong reference: the check and the use see the same player.

03:09 So cleanup that must happen can’t wait for the collector. JavaScript’s try/finally works as Python’s does: finally runs however try ends.

03:20 Write the log, then close it in finally: the closing line follows the writing line, every run. In Python, a context manager can hide that finally behind a with statement.

03:32 JavaScript’s newer using declaration plays that role, a topic for another time.

03:39 A registry still works as a safety net, for a log someone forgets to close. Python’s weakref.finalize() returns a handle you can detach().

03:49 register() returns nothing, so you pass a token, a key you keep to cancel later, while the log is alive. After the explicit close, unregister() with that token cancels the callback and returns true.

04:03 As with weakref.finalize()’s arguments, the held value must not refer to the log. JavaScript checks one case: the log itself throws a TypeError.

04:14 An object holding the log keeps it alive, so its callback never runs, not even at exit, where Python’s would.

04:23 So weak references observe objects; they never clean up after them. Read a WeakRef once into a local and handle undefined. Close what you open with try/finally, and treat a finalizer as a safety net that may never run.

04:39 Next up is the exercise Keep Player Notes Separate, where updating one player’s notes must keep the other player’s intact.

Become a Member to join the conversation.