Releasing a Lock With using
A try/finally releases the lock, but the next function that needs a job’s lock would have to
write it all again. Priya’s Python doesn’t, because JobLock is a context manager: with calls
__enter__() to take the lock and __exit__() to release it.
JavaScript’s counterpart has only the release half. The constructor takes the lock, as
__enter__() does, with the lines that took it in runJob(), and a method keyed by
Symbol.dispose, a built-in symbol, releases it with the lines that released it.
Python marks its hooks with double underscores; JavaScript uses a symbol, so no ordinary method
name can match it. The square brackets make it a computed key. Unlike __exit__(), the method
takes no arguments. An object with this method is a disposable:
class JobLock {
constructor(jobId) {
this.name = `${jobId}.lock`;
this.path = join(LOCKS, this.name);
writeFileSync(this.path, "", { flag: "wx" });
console.log(` [lock] took ${this.name}`);
}
[Symbol.dispose]() {
unlinkSync(this.path);
console.log(` [lock] released ${this.name}`);
}
}