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:
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:
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:
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");