Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Cleanup
- Releasing an acquired resource, such as a scratch-buffer lease, file or destination lock.
- Early exit
- A return or failure path that leaves before the function’s final ordinary statement.
- Reverse order
- Ending acquired resources from the most recently acquired to the earliest.
- finally
- A block executed as its try/catch leaves; control flow inside it can replace a pending failure.
Tie cleanup to the work that owns a resource
Acquiring a resource creates a release responsibility: return a leased buffer, unlock a lock or close a file. Identify which operation owns that responsibility and how long its work needs the resource. A release placed only after successful work can miss an earlier exit.
try/finally arranges cleanup when control leaves the try, including through an exception or return. Place acquisition and use so the finally belongs to the operation that actually owns the resource. Cleanup should preserve the caller’s success or failure report.
01Early exits
A failure can skip a release at the function end
A configuration importer borrows scratch storage to decode each key=value entry before writing it to a destination cache. A malformed entry can leave that storage leased after its caller has already reported failure. The importer also needs to acquire a destination lock and keep a batch moving after one bad record.
The importer stores port=8080 and then attempts malformed badline. The decoder reads the actual leased working text. Track which pool entries remain after those calls leave.
storeAssignment may throw when the leased text is malformed.
export {};
// Supplied single-threaded importer resources. Leased buffers own the working text.
const buffers = new Map<number, string>();
const caches = new Map<string, Map<string, string>>([
['local', new Map()],
['shared', new Map()]
]);
let serial = 0;
let currentBuffer = 0;
function takeBuffer(source: string): number {
currentBuffer = ++serial;
buffers.set(currentBuffer, source);
return currentBuffer;
}
function releaseBuffer(lease: number, trace = false): void {
const source = buffers.get(lease);
if (!buffers.delete(lease)) {
if (trace) console.log('invalid buffer release');
return;
}
if (trace) console.log(`buffer released from ${source}`);
}
// Supplied work: decode the leased text, store its fields, then read the stored value.
function storeAssignment(): string {
const text = buffers.get(currentBuffer);
if (text === undefined) throw new Error('no scratch lease');
const fields = text.split('=');
if (fields.length !== 2 || fields[0] === '' || fields[1] === '') {
throw new Error('invalid assignment');
}
const cache = caches.get('local')!;
cache.set(fields[0], fields[1]);
return `${fields[0]}=${cache.get(fields[0])}`;
}
function importOne(source: string): void {
const lease = takeBuffer(source);
console.log(`${storeAssignment()} stored`);
releaseBuffer(lease);
}
for (const source of ['port=8080', 'badline']) {
try {
importOne(source);
} catch (error) {
console.log(`${source}: ${(error as Error).message}`);
}
}
console.log(`leased ${buffers.size}`);
npx tsc main.ts --strict --target ES2022 --module Node16 --moduleResolution Node16 --types node --outDir out && node out/main.js
Use a fresh directory and replace main for each probe. For TypeScript, set package.json’s type field to commonjs while preserving other fields, use the installed TypeScript and Node types, and run the guarded emit command. The Go and Rust commands use one supplied main file. The importer is synchronous; its releases complete normally. Process termination, concurrent use and failures inside cleanup are outside these probes.
02On normal exits
Arrange a release that runs as the operation leaves
The next version ties release to leaving the import operation. The malformed entry still needs its failure report; trace which output happens first.
The lease is released by finally.
export {};
// Supplied single-threaded importer resources. Leased buffers own the working text.
const buffers = new Map<number, string>();
const caches = new Map<string, Map<string, string>>([
['local', new Map()],
['shared', new Map()]
]);
let serial = 0;
let currentBuffer = 0;
function takeBuffer(source: string): number {
currentBuffer = ++serial;
buffers.set(currentBuffer, source);
return currentBuffer;
}
function releaseBuffer(lease: number, trace = false): void {
const source = buffers.get(lease);
if (!buffers.delete(lease)) {
if (trace) console.log('invalid buffer release');
return;
}
if (trace) console.log(`buffer released from ${source}`);
}
// Supplied work: decode the leased text, store its fields, then read the stored value.
function storeAssignment(): string {
const text = buffers.get(currentBuffer);
if (text === undefined) throw new Error('no scratch lease');
const fields = text.split('=');
if (fields.length !== 2 || fields[0] === '' || fields[1] === '') {
throw new Error('invalid assignment');
}
const cache = caches.get('local')!;
cache.set(fields[0], fields[1]);
return `${fields[0]}=${cache.get(fields[0])}`;
}
function importOne(source: string): void {
const lease = takeBuffer(source);
try {
console.log(`${storeAssignment()} stored`);
} finally {
releaseBuffer(lease, true);
}
}
for (const source of ['port=8080', 'badline']) {
try {
importOne(source);
} catch (error) {
console.log(`${source}: ${(error as Error).message}`);
}
}
console.log(`leased ${buffers.size}`);
03Cleanup scope
Cleanup can run too early, too late or hide the failure
The same release mechanism can end at the wrong boundary or change the report. Inspect each proposed use before applying it to a batch.
The finally block returns done.
export {};
// Supplied single-threaded importer resources. Leased buffers own the working text.
const buffers = new Map<number, string>();
const caches = new Map<string, Map<string, string>>([
['local', new Map()],
['shared', new Map()]
]);
let serial = 0;
let currentBuffer = 0;
function takeBuffer(source: string): number {
currentBuffer = ++serial;
buffers.set(currentBuffer, source);
return currentBuffer;
}
function releaseBuffer(lease: number, trace = false): void {
const source = buffers.get(lease);
if (!buffers.delete(lease)) {
if (trace) console.log('invalid buffer release');
return;
}
if (trace) console.log(`buffer released from ${source}`);
}
// Supplied work: decode the leased text, store its fields, then read the stored value.
function storeAssignment(): string {
const text = buffers.get(currentBuffer);
if (text === undefined) throw new Error('no scratch lease');
const fields = text.split('=');
if (fields.length !== 2 || fields[0] === '' || fields[1] === '') {
throw new Error('invalid assignment');
}
const cache = caches.get('local')!;
cache.set(fields[0], fields[1]);
return `${fields[0]}=${cache.get(fields[0])}`;
}
function importOne(source: string): string {
const lease = takeBuffer(source);
try {
storeAssignment();
return 'stored';
} finally {
releaseBuffer(lease);
return 'done';
}
}
for (const source of ['port=8080', 'badline']) {
try {
console.log(`${source} ${importOne(source)}`);
} catch (error) {
console.log(`${source}: ${(error as Error).message}`);
}
}
console.log(`leased ${buffers.size}`);
04Repair the configuration importer
Release a buffer, release acquired resources in order, then scope every record
Repair the synchronous importer in three focused files. Protect one scratch lease, then handle partial acquisition of a destination lock. The batch must give every record its own resource lifetime and still reach records after a failed decode.
The pool owns the decoder’s working text. The supplied store function checks that the lease and any required lock are held, then returns a cache readback.
Repair the configuration importer
Protect a single operation, account for acquired resources, then preserve cleanup and progress across a batch.
Sign in to keep your read marks on every device. Sign in
Was this helpful?