Terminology (5)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.
- Root
- A live reference preserved directly by the runtime, such as a local needed across a collection point, a global or a runtime-owned slot. A variable’s lexical scope alone is insufficient.
- Reachable
- Led to by some chain of references from a root.
- Tracing collection
- Marking everything reachable from the roots and reclaiming the rest.
- Reference counting
- Tracking how many references point at a value and freeing it when the count reaches zero.
- Weak reference
- A reference that lets the program find an object without keeping it alive.
How reclamation finds live data
A tracing collector starts from live roots: references the runtime must preserve directly. Following strong references from those roots identifies reachable objects. An object’s usefulness to the application is a separate question from whether a path still reaches it.
Reference counting instead tracks strong owners of a managed value. Weak references permit optional lookup without being strong owners. These mechanisms answer different lifetime questions; eligibility for tracing reclamation, target destruction and the time a program observes absence must be distinguished.
01Cycles
Does a cycle keep itself alive?
An order has shipped, and the service removes it from its pending-order registry. The order still points to its customer, whose order list points back. Follow the remaining strong paths before deciding whether the pair can be reclaimed. Then ask what a preview cache should observe when it has only a weak link to a target that collection actually removes.
A simple tracing collection starts from live roots and follows strong references to identify what must be kept. Other objects are eligible for reclamation; real runtimes choose their collection work and timing. Reference counting releases a managed value when its strong owner count reaches zero.
Each program models one piece of the order service: a request loads a customer and an order and links them both ways, so a page can list a customer’s orders and show an order’s customer. Then the request ends and nothing else refers to either.
WeakRef observes an optional target without permanently owning it. Creating/dereferencing it keeps the returned target available through the current job; the program crosses task boundaries before asking for collection. Clearing is still not guaranteed. gc() is only exposed by the shown Node flag.
// The order service links each customer to its orders and each order back to its
// customer. A request handler builds one pair, then returns.
// Run with node --expose-gc so the program can ask for a collection.
type Customer = {
id: number;
orders: Order[];
};
type Order = {
id: number;
customer: Customer;
};
const watched: WeakRef<object>[] = [];
function handleRequest(): void {
const customer: Customer = { id: 17, orders: [] };
const order: Order = { id: 1001, customer };
customer.orders.push(order);
watched.push(new WeakRef(customer), new WeakRef(order));
}
const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));
async function main(): Promise<void> {
handleRequest();
await nextTask();
(globalThis as { gc?: () => void }).gc?.();
await nextTask();
console.log(`customer still alive: ${watched[0].deref() !== undefined}`);
console.log(`order still alive: ${watched[1].deref() !== undefined}`);
}
void main();
npx tsc main.ts --noEmit --strict && node --expose-gc main.ts
The quoted outputs are historical observations, not new runs in this revision. Node --expose-gc exposes a collection request; it does not promise WeakRef clearing. Go’s runtime.GC plus a 50-millisecond sleep does not guarantee AddCleanup callbacks run before printing or program exit. Use these probes to inspect an observation, not as deterministic lifetime tests.
02Roots
Where does reachability start?
Roots are live references the runtime must preserve directly, such as a handler local needed after a collection point, a global registry and runtime-owned slots. A local can cease to be live at its last use before the surrounding function ends; Go’s runtime.KeepAlive can explicitly extend liveness to a point. An object is reachable when some chain of references leads to it from a root. How many references point at it does not matter.
| Language | Freed when | Unreachable cycles |
|---|---|---|
| TypeScript | Eligible without a live strong path; engine timing/weak clearing is not guaranteed | Eligible for tracing reclamation |
| Go | Eligible without a live strong path; GC and asynchronous cleanup observations differ | Eligible for tracing reclamation |
| Rust | Its owner goes out of scope; for Rc and Arc, the strong count reaches zero | Rc and Arc cycles are leaked |
| C++ | Its owner is destroyed or delete runs; for shared_ptr, the use count reaches zero | shared_ptr cycles are leaked |
03Weak references
How do you refer to something without keeping it?
A weak reference can resolve to a target while that target remains available, without being a strong owner. A successful lookup gives a temporary strong reference/owner for use. It does not promise that an eligible target has already been collected; missing results must be handled.
That is what a cache of rendered order previews needs: reuse a preview while a request still holds it, without keeping every preview the service has rendered.
JavaScript has WeakRef for optional target lookup and WeakMap for weak-key associations; these are different APIs. Go has weak.Pointer, Rust has Weak, and C++ has std::weak_ptr. Check deref/Value/upgrade/lock results before use. Rc/shared_ptr weak observers may keep control metadata allocated after the target value is destroyed.
04Practice
Finish the heap-snapshot tool
The order service’s memory grows in staging, and the team reads heap snapshots to find out why. The lab is their snapshot tool, working on a model of the service’s heap, not a real one. It reads a snapshot from stdin (the objects, their references, and what handlers and globals hold), counts references, collects, and follows the preview cache’s weak references. Each level supplies the parts that already work.
The heap-snapshot tool
Count references, collect from the roots, then let weak references go.
In the frontend Handle a missing weak-cache preview Optional
The preview button checks a weak-value cache when clicked and displays either the title or a reload request. Read deref once into a local before using the target. The result describes this lookup; it is not a subscription to collection or a deadline for disappearance. The Map still strongly owns its string keys and WeakRef wrappers, so this example does not provide a bounded cache policy.
"use client";
import { useState } from "react";
type Preview = { title: string };
export default function PreviewButton({
cache,
id
}: {
cache: Map<string, WeakRef<Preview>>;
id: string;
}) {
const [label, setLabel] = useState("Check preview");
function check() {
const preview = cache.get(id)?.deref();
setLabel(preview ? preview.title : "Reload required");
}
return <button onClick={check}>{label}</button>;
}
The state stores a title string, while the successful local lookup makes the preview usable during this job. Another click may observe the same target, a replacement wrapper or absence; no forced collection is assumed.
Sources: ECMAScript: WeakRef operations and kept objects,React: useState,Svelte: state.
Sign in to keep your read marks on every device. Sign in
Was this helpful?