Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Preface

This book explains how paragc works, from the first alloc to a heap shared by several processes. It is written for two kinds of readers:

  • Users who embed paragc in a Rust program (a language runtime such as j8, a database, a graph library) and want to know what each API promises and what it costs.
  • Contributors who want to change the collector and need the invariants that hold it together.

paragc is a tracing garbage collector with an Immix-style mark-region heap. Many threads allocate at once, collections mark and sweep on every core, and nothing in it takes a lock. On Linux, the crossheap feature adds heaps that live in shared memory: other processes map them, read and write their objects, and find objects by a signature.

How to read it

PartWhat it covers
Garbage collectionWhat a garbage collector is and the concepts every collector is built from; the first collectors (1960 onwards); the JVM’s collectors; cppgc, V8’s C++ heap; and how paragc descends from them
Getting startedWhat paragc is, a first program, the handle types and why they carry brands
The private heapThe in-process heap: layout, allocation, marking, sweeping, concurrent work, evacuation, young collections, reference counting, weak references
Between heapsDirect references from one private heap into another, and collecting cycles that span them
Cross-heapHeaps on shared memory: address space, file layout, objects without code, processes that die at any moment, weak references and signatures across processes, promotion of private objects into a cross-heap
Quality and roadmapTests, Miri, benchmarks, code rules, known limits and what comes next

Every page states the current behaviour of the code on main. When a page and the code disagree, the code wins; please open an issue or use the edit link at the top of the page.

Versions

This edition describes paragc 0.6.1:

  • 0.6.0 added cross-heap weak references, signatures, the mailbox, shrinking and promotion;
  • 0.6.1 added tail allocation.

The crate is on crates.io and its API reference is on docs.rs.

What a garbage collector is

A program allocates memory for its data: a list node, a string, an object. At some point the data is no longer needed and the memory should be reused. Someone has to decide when.

  • In C, the programmer decides: malloc gives memory, free gives it back. Free too early and the program reads memory that now belongs to something else (use-after-free). Forget to free and memory leaks. Free twice and the allocator’s own bookkeeping breaks.
  • In Rust, the compiler decides for most data: every value has one owner, and the value is dropped when the owner goes out of scope. This works as long as the data forms a tree. Graphs with cycles, or data shared without a clear owner, need Rc/Arc (reference counting) or an arena, each with its own limits.
  • A garbage collector (GC) decides at run time, by looking at the data itself. Memory that the program can no longer reach is garbage; the collector finds it and reuses it. The program only allocates and never frees.

The program is called the mutator: from the collector’s point of view, all it does is change (mutate) the graph of objects. The collector is the other party, which reclaims what the mutator can no longer use.

Reachability

A collector cannot know which objects the program will use in the future; that is undecidable in general. It uses a safe approximation instead: an object is live if the program could still reach it.

  • Roots are the places the program reads directly: local variables on the stacks, registers, globals, and, in a library like paragc, handles the program explicitly registers (Root).
  • An object is reachable if a chain of pointers leads to it from a root.
  • Everything else is garbage. No chain of pointers leads to it, so the program cannot touch it again, and reusing its memory is safe.

Reachable objects may still never be used again. That memory is a leak a GC cannot fix, but it is never a crash.

The two families: tracing and reference counting

TracingReference counting
Ideafrom time to time, start at the roots, follow every pointer, and mark what you reach; the rest is garbageevery object counts the pointers to it; at zero it is garbage
Work is proportional tolive data (marking) and heap size (sweeping)the number of pointer writes
Cyclescollected naturallynever reach zero: leak unless another mechanism handles them
When memory comes backat the next collectionimmediately when the count drops
Cost on the mutatorsmall (barriers only for some designs)every pointer write updates two counts

Real collectors mix the two. CPython counts references and traces for cycles. LXR, which paragc follows, counts references for old objects and traces now and then.

Tracing collectors: what happens to the garbage

After marking, a tracing collector has three choices.

AlgorithmWhat it doesProsCons
Mark-sweepwalk the heap and put every unmarked object on a free listobjects never movefragmentation; allocation searches free lists
Mark-compactslide live objects together at one end of the heapno fragmentation; bump allocationseveral passes over the heap; every pointer must be updated
Copying (semispace)copy live objects into an empty space while tracing; the old space is wholly freeone pass, work proportional to live data only; bump allocationhalf the memory sits empty; long-lived objects get copied again and again
Mark-region (Immix)free memory in units of fixed-size lines inside blocks; copy only when a block is sparsebump allocation into free lines; little copyingan object can leave a partly used line unusable

Allocation

  • Free-list allocation searches lists of free chunks by size: flexible but slow, and it fragments.
  • Bump allocation keeps a pointer and a limit and moves the pointer forward: a compare and an add. It needs contiguous free space, which is why compacting, copying and region collectors are fast to allocate from.
  • Thread-local allocation buffers (TLABs): each thread bumps inside its own chunk, so allocation needs no synchronization at all.

When the collector runs

StyleMeaning
Stop-the-worldall mutator threads stop while the collector works. Simplest; the stop is a pause
Parallelthe collector uses several threads during a pause. The pause is shorter; the mutators are still stopped
Incrementalthe collector works in small slices interleaved with the mutator, one thread at a time
Concurrentthe collector runs on other threads while the mutators keep running

Stopping the mutators safely needs safepoints: places in the program where every thread’s roots are known. Runtimes like the JVM poll at loop back-edges and calls. paragc avoids them: Rust’s borrow checker proves that no mutator is inside the heap when a stop-the-world collection runs.

Tri-color marking and barriers

Dijkstra and his colleagues described tracing with three colors:

  • white: not reached yet (garbage, if it stays white);
  • grey: reached, but its pointers have not been scanned;
  • black: reached and fully scanned.

Marking ends when nothing is grey. When the mutator runs during marking (incremental or concurrent), it can hide an object: it stores a pointer to a white object into a black one and deletes the only other path. The collector would never see it and would free a live object. Barriers prevent this. A barrier is a few instructions the compiler or library runs on every pointer write (write barrier) or read (read barrier):

BarrierWhat it does
Insertion (Dijkstra)when a pointer is stored, shade the new target grey
Deletion / snapshot at the beginning (Yuasa)when a pointer is overwritten, shade the old target grey. Everything reachable when marking began survives
Read barrier (Baker, Brooks, load barriers)when a pointer is loaded, make sure it points at the current copy of a moved object

Objects allocated during marking are usually made black right away (black allocation).

Generations

The weak generational hypothesis says that most objects die young. A generational collector:

  • splits the heap into a young generation (the nursery) and one or more old generations;
  • collects the young generation often and cheaply (a minor or young collection), and the whole heap rarely (a major or full collection);
  • moves objects that survive a few young collections into the old generation (promotion).

A young collection does not trace the old generation, so it must know about pointers from old objects to young ones. The write barrier records them in a remembered set, or marks the containing chunk of memory dirty in a card table.

Precise or conservative

  • A precise (exact) collector knows exactly which words are pointers: the compiler emits stack maps, or the library keeps handles. It can move objects, because it can update every pointer.
  • A conservative collector treats any word that looks like a pointer into the heap as one, typically on the stack, where it lacks type information. It cannot move an object that such a word points at, since that word might really be an integer.

Moving or not

Moving objects (copying, compacting, evacuating) removes fragmentation and allows bump allocation, but it changes addresses. Everything that holds an address must be updated, and nobody outside the collector’s knowledge may keep a raw address across a collection. Non-moving collectors are simpler to embed, especially in C++, where raw pointers are everywhere.

Finalization and weak references

  • A finalizer (destructor) runs when the collector frees an object: to close a file, release a lock, free native memory. The collector decides when, and in no particular order, so a finalizer must not depend on other collected objects.
  • A weak reference points at an object without keeping it alive. After a collection it either still points at the object or is cleared. Caches and observer lists use them.

What a collector is judged on

MeasureQuestion
Throughputwhat fraction of time goes to the program rather than the collector?
Latencyhow long are the pauses, and how often?
Footprinthow much memory beyond the live data does it need?
Mutator overheadwhat do barriers and allocation cost the program?
Scalabilitydoes it use all the cores, for allocation and for collection?

No design wins on all five. Every collector in the next chapters makes a different trade between them.

The first garbage collectors

Garbage collection is almost as old as high-level programming. Most of the ideas used today were invented between 1960 and 1990.

1960: Lisp and mark-sweep

John McCarthy’s Lisp, described in Recursive Functions of Symbolic Expressions and Their Computation by Machine (1960), built all data from cons cells and gave the programmer no way to free them. When the free list ran out, the system:

  1. started from the program’s registers and variables;
  2. followed every car and cdr pointer, setting a mark bit in each cell it reached;
  3. swept through all of memory, putting every unmarked cell back on the free list.

That is mark-sweep, the first garbage collector, implemented on the IBM 704. It stopped the program for the whole collection. The paper called the process “reclamation”; the name “garbage collection” came soon after.

1960: reference counting

In the same year George Collins published A Method for Overlapping and Erasure of Lists. Each cell counts the pointers to it, and a cell whose count reaches zero is freed at once, together with whatever only it pointed to. No pause, but every pointer change costs work, and cycles are never freed. Reference counting has lived on ever since: in Smalltalk-80, Objective-C and Swift (ARC), CPython, C++ shared_ptr and Rust’s Rc/Arc.

1963–1970: copying collectors

  • Marvin Minsky (1963) collected a Lisp heap by copying the live cells out to secondary storage and back.
  • Robert Fenichel and Jerome Yochelson (1969) split memory into two semispaces. Allocation fills one; a collection copies everything reachable into the other, and the roles swap.
  • C. J. Cheney (1970) made the copy breadth-first and non-recursive: the to-space itself serves as the queue of objects still to scan, so no stack is needed.

Copying collection touches only live objects and leaves free memory in one piece, so allocation becomes a pointer bump. The price is half the memory standing idle.

1970s: compaction

Mark-compact algorithms slide live objects to one end of the heap without a second space. The LISP 2 algorithm computes new addresses in one pass, updates pointers in a second and moves objects in a third. Jonkers (1979) and others reduced the passes with pointer threading. Compaction keeps allocation fast without the semispace’s memory cost.

1975–1978: collecting while the program runs

  • Guy Steele (1975) and Edsger Dijkstra, Leslie Lamport and colleagues (On-the-Fly Garbage Collection, 1978) described collectors that run concurrently with the program. Dijkstra’s paper introduced the tri-color abstraction and the insertion write barrier.
  • Henry Baker (1978) made copying incremental and real-time: the collector copies a little on each allocation, and a read barrier makes sure the program only ever sees the new copy of an object.
  • Taiichi Yuasa (1990) published the deletion barrier that underlies snapshot-at-the-beginning marking.

1983–1984: generations

Henry Lieberman and Carl Hewitt (1983) observed that most objects die young and proposed collecting recent objects more often. David Ungar’s Generation Scavenging (1984), in Berkeley Smalltalk, made it practical: a small nursery is copied often, survivors are promoted, and a remembered set records old-to-young pointers. Almost every production collector since has been generational.

1988: conservative collection for C

Hans Boehm, Alan Demers and Mark Weiser built a collector for C and C++ programs that were never designed for one. It scans stacks, registers and data segments conservatively: any word that looks like a heap address keeps that object alive. It never moves objects. The Boehm GC is still used by GNU Guile, Mono (in the past), Inkscape and many language runtimes.

1990s–2000s: towards the modern design

  • Parallel collectors used several threads during the pause, with work stealing to balance load (Endo et al., 1997; Flood et al., 2001).
  • Mostly concurrent mark-sweep (Boehm et al., 1991; Printezis & Detlefs, 2000) became the basis of the JVM’s CMS.
  • Region-based heaps let a collector reclaim or evacuate parts of the heap independently. They lead to G1 in the JVM.
  • Immix (Stephen Blackburn and Kathryn McKinley, 2008) introduced the mark-region heap: blocks cut into lines, bump allocation into free lines, and opportunistic copying of sparse blocks. paragc’s heap is an Immix heap.
  • LXR (Wenyu Zhao, Stephen Blackburn and Kathryn McKinley, 2022) combined Immix with reference counting for old objects and occasional concurrent tracing, and showed low latency without giving up throughput. paragc follows its first three stages.

The textbook

Richard Jones, Antony Hosking and Eliot Moss, The Garbage Collection Handbook (2nd edition, 2023), covers all of the above in depth and is the standard reference.

The JVM’s collectors

The Java Virtual Machine is where garbage collection was industrialised. A JVM runs many threads, allocates at enormous rates, and serves both batch jobs that want throughput and servers that want short pauses. Instead of one collector, HotSpot (OpenJDK’s JVM) offers several, chosen with a command-line flag. Together they show the whole design space.

Common machinery

MechanismWhat it is
Precise rootsthe JIT emits stack maps; at a safepoint every pointer on every stack is known
Safepointscompiled code polls at loop back-edges and method returns; a collection stops all threads at safepoints
TLABseach thread bump-allocates in its own thread-local allocation buffer inside the young generation
Card tablethe old generation is divided into 512-byte cards; the write barrier dirties a card when a pointer is stored into it, so young collections only scan dirty cards
Generationsa young generation (Eden + two survivor spaces, copied) and an old generation

Serial

One thread does everything while all mutators stop. The young generation is copied (Eden and one survivor space into the other survivor space or the old generation); the old generation is mark-compacted. It is the right choice for small heaps and single-core machines, and it still runs in containers with little CPU.

Parallel (the throughput collector)

The same algorithms as Serial, but the pause uses every core, with work stealing. It gives the best total throughput, at the cost of pauses that grow with the heap. It was the default collector up to JDK 8.

CMS: Concurrent Mark Sweep

CMS (JDK 1.4) marked the old generation concurrently with the program, using an incremental-update write barrier, with short pauses at the start (initial mark) and end (remark), and then swept concurrently. It never compacted the old generation, so it suffered from fragmentation and had to fall back to a long full collection when allocation failed. It was deprecated in JDK 9 and removed in JDK 14.

G1: Garbage First

G1 (experimental in JDK 6u14, default since JDK 9) splits the heap into equal regions (1–32 MiB).

  • Regions take the role of Eden, survivor or old as needed; humongous objects take runs of regions.
  • Each region has a remembered set of incoming pointers, so any set of regions can be evacuated on its own.
  • Marking is concurrent with snapshot-at-the-beginning (SATB) barriers.
  • Each pause evacuates a collection set: all young regions plus the old regions with the most garbage (hence the name), chosen to fit a pause-time goal (-XX:MaxGCPauseMillis, 200 ms by default).
  • Compaction happens incrementally by evacuation, so fragmentation stays under control.

G1 is a balance between throughput and latency, and it is the default for most workloads.

ZGC

ZGC (experimental in JDK 11, production in JDK 15, generational since JDK 21) aims for pauses under a millisecond, independent of heap size, up to multi-terabyte heaps.

  • Coloured pointers: metadata bits inside each 64-bit reference record its marking and relocation state.
  • Load barriers: every pointer loaded from the heap is checked. If it is stale, the barrier fixes it on the spot by finding or making the relocated copy.
  • Marking, relocation and reference updating are all concurrent. Pauses only handle roots, and their length does not depend on heap size.

Shenandoah

Shenandoah (Red Hat, JDK 12) also evacuates concurrently with the program. It started with Brooks forwarding pointers (an extra word per object pointing at its current copy) and moved to load-reference barriers like ZGC. It became generational in recent releases.

Epsilon

Epsilon (JDK 11) allocates and never collects. It exists for performance testing and for very short-lived programs.

What the JVM teaches

  • There is no single best collector; throughput, latency and footprint pull in different directions.
  • Generations, TLABs, card tables and remembered sets are the standard toolkit.
  • Low pause times need concurrent moving, which needs read barriers on every load. The JIT can afford those because it compiles every access.

paragc borrows the toolkit: TLAB-style buffers, remembered sets, SATB marking, parallel work stealing. It does not borrow read barriers. It is a library, not a JIT, and cannot instrument every pointer load, so it only moves objects while the mutators are stopped.

cppgc: V8’s C++ heap

A JVM controls the language, the compiler and the runtime, so it can put barriers and stack maps everywhere. A garbage collector for C++ cannot. The code is written by people, pointers are raw, and the stack is whatever the C++ compiler made of it. cppgc, also known as Oilpan, is the best-known modern answer, and the closest relative of paragc.

Where it comes from

Chrome’s rendering engine, Blink, used reference counting for its DOM objects, and cycles between C++ DOM nodes and JavaScript wrappers leaked. Around 2013 the Blink team built Oilpan, a tracing garbage collector for Blink’s C++ objects. In 2020 it moved into V8 as the standalone library cppgc, so other embedders could use it too. Today Blink’s DOM, the V8 JavaScript heap and cppgc’s C++ heap form one unified heap, traced together.

The programming model

class Node final : public cppgc::GarbageCollected<Node> {
 public:
  void Trace(cppgc::Visitor* visitor) const {
    visitor->Trace(next_);
  }
 private:
  cppgc::Member<Node> next_;
};

auto* node = cppgc::MakeGarbageCollected<Node>(heap->GetAllocationHandle());
cppgc::Persistent<Node> root(node);
cppgcRoleparagc counterpart
GarbageCollected<T>base class of heap objects#[derive(Trace)]
Trace(Visitor*)written by hand, reports each pointer fieldgenerated by the derive
Member<T>pointer field inside a heap object, with a write barrierSlot<'gc, T>
WeakMember<T>weak fieldWeak inside an object
Persistent<T>root held from outside the heapRoot<B>
WeakPersistent<T>weak rootWeak<B>
raw T* on the stackfound by conservative stack scanningGc<'gc, T>, safe only inside mutate

How it collects

  • Mark-sweep with free-list allocation in size-class pages, plus bump allocation in linear allocation buffers. Ordinary objects do not move.
  • Conservative stack scanning: any word on a thread’s stack that points into the heap keeps that object alive. This is what lets C++ code hold raw pointers in local variables safely, and it is also why objects cannot move freely.
  • Incremental and concurrent marking with write barriers on Member stores, and concurrent sweeping.
  • Compaction only for backing stores: the buffers behind Blink’s vectors and hash tables can be compacted, because cppgc knows every slot that points at them.
  • Pre-finalizers run before sweeping, while every object is still intact, for cleanup that must touch other heap objects. Ordinary destructors run during sweeping, in no particular order.
  • A young generation (minor collections with a remembered set) exists behind a build flag and needs the caged heap: all objects in one large reservation, so a pointer can be checked against the heap with a mask.

What cppgc teaches

  • A C++ collector has to tolerate raw pointers on the stack, so it scans conservatively, and that limits moving.
  • Hand-written Trace methods are a frequent source of bugs: forgetting a field means a live object gets freed.
  • One unified heap across languages (C++ and JS) removes the leaks that two separate collectors with cross-references produce.

Where paragc differs

cppgcparagc
Stackscanned conservativelynot scanned; Gc handles are confined to mutate by Rust lifetimes
Stop-the-worldneeds every thread at a known point&mut Heap: the borrow checker proves nobody is inside
Movingordinary objects never moveevacuation and young copying, because no unknown raw pointers exist
Tracing codehand-written Tracederived; Drop on traced types rejected at compile time
Allocation threadsper-thread heapsone heap, many threads bump-allocating at once
Young objectsoptional minor GCsticky-mark young collections and reference counting by default
Sharing between processesnonecross-heaps on shared memory (Linux)

Rust gives paragc what cppgc has to buy with conservative scanning: the compiler knows when no pointer can be outside the collector’s view.

From there to paragc

paragc is assembled from ideas in the previous chapters, plus one that only Rust allows. This page maps each part of paragc to where it comes from; the rest of the book explains each part in detail.

What paragc takes

IdeaOriginIn paragc
Tracing from rootsMcCarthy, 1960every collection marks from Roots, entries and remembered slots
Tri-color marking, SATB barrierDijkstra et al. 1978; Yuasa 1990concurrent marking with a deletion barrier on Slot writes and black allocation (Concurrent)
Bump allocation in thread-local bufferscopying collectors; JVM TLABsTlab, one per thread in mutate (Allocation)
Mark-region heap: blocks and linesImmix, 200832 KiB blocks, 256 B lines, overflow allocation (Layout)
Opportunistic evacuationImmixsparse blocks copied while marking (Evacuation)
Generations, remembered setsLieberman & Hewitt; Ungarsticky-mark young collections, slot logging (Young collections)
Parallel marking with work stealingEndo, Flood et al.; JVM Parallel and G1crossbeam deques per worker (Marking)
Reference counting for old objects, background releaseCollins 1960; LXR 20226-bit counts settled at young collections, decrements on the pool (Reference counting)
Weak referencesLisp weak pointers; Java WeakReferenceWeak, cleared in every pause (Weak references)
A collector as a library for a host languageBoehm GC, cppgca Rust crate; j8 builds its JS heap on it

What paragc adds

The borrow checker as the stop-the-world. JVMs need safepoints and stack maps. cppgc needs conservative stack scanning. paragc needs neither:

  • a Gc<'gc, T> cannot leave the mutate call it came from, so outside mutate no unregistered pointer exists;
  • a stop-the-world collection takes &mut Heap, so the compiler proves no mutate is running.

That is why paragc can move objects (evacuation, young copying) without read barriers and without conservative pinning, as a plain library.

No locks anywhere. Many mutators allocate at once from one heap. Blocks, roots, weak references and work queues are lock-free structures, and the thread pool is woken with one atomic word.

Heaps in shared memory, across processes. No collector in the previous chapters lets several processes use one heap at once. paragc’s cross-heaps do:

  • objects without code pointers, collected by pointer maps;
  • offsets that mean the same thing in every process;
  • crash recovery when a process dies mid-collection;
  • weak references and signatures that never make one process wait for another;
  • promotion of a private heap’s survivors into a cross-heap.

The rest of the book starts from the user’s side (Quick start), then goes through the private heap, references between heaps, and the cross-heap.

What paragc is

paragc is a tracing garbage collector for Rust programs that share one heap across many threads.

  • Objects live in 32 KiB blocks cut into 256-byte lines, the layout of Immix (Blackburn & McKinley, 2008).
  • Threads bump-allocate into free lines on their own.
  • A collection marks and sweeps on every core.

What sets it apart

Many mutatorsHeap::mutate(&self) runs on any number of threads at once. Each thread allocates from its own buffer (Tlab) and claims whole blocks with one atomic operation.
Exclusive by borrowingHeap::collect(&mut self) cannot overlap a mutate, because the borrow checker forbids it. That borrow is the stop-the-world: there is no safepoint protocol and no lock.
Concurrent markingHeap::mark_concurrently(&self) marks while mutators keep running. A snapshot-at-the-beginning barrier on Slot writes keeps it correct, and new objects are allocated black.
Concurrent sweepingHeap::finish_marking only finishes marking. Mutators sweep a block themselves when they need one, and sweep_concurrently sweeps the rest on the pool.
EvacuationA stop-the-world collection copies live objects out of sparse blocks while it marks (Immix defragmentation).
Young collectionscollect_young traces only objects allocated since the last collection and compacts the survivors.
Reference countingOld objects carry a small count, settled at young collections and released in the background (the LXR design). Full tracing only runs every few rounds, for cycles.
Weak referencesWeak<B> does not keep its target alive; every kind of collection clears or moves it.
References between heapsFar points straight from one private heap into another; collect_group reclaims cycles across them.
Cross-heap (Linux)A CrossHeap lives in a shared-memory file. Several processes map it and use it at once, a killed process never blocks the others, and objects can be signed and found from another process.

Where it is used

paragc is the heap of the j8 JavaScript engine. In j8:

  • every JS object, string and closure is a paragc object;
  • one isolate owns one Heap;
  • with the crossheap feature, the isolate attaches a cross-heap as its old generation. JS values that survive a turn are promoted there, so another process can read them by signature.

What it is not

  • Not a conservative collector. paragc does not scan stacks. Every object that must survive a collection is reachable from a Root. Inside a mutate, Gc handles are safe because no collection can run.
  • Not no_std. It needs threads, mmap and atomics from std.
  • Not a drop-in Rc replacement. Objects are reached through branded handles. Types implement Trace (usually with #[derive(Trace)]), and a type with Gc fields must not implement Drop.

Quick start

[dependencies]
paragc = "0.6"

A singly linked list, kept by a root and summed after a collection:

#![allow(unused)]
fn main() {
use paragc::{Gc, Heap, Root, Trace, brand};

#[derive(Trace)]
struct Node<'gc> {
    value: u64,
    next: Option<Gc<'gc, Node<'gc>>>,
}

// A root handle has no 'gc; the brand puts it back on when you read it
brand!(NodeB = for<'gc> Node<'gc>);

let mut heap = Heap::default();
let list: Root<NodeB> = heap.mutate(|m| {
    let mut head = None;
    for value in 0..1000 {
        head = Some(m.alloc(Node { value, next: head }));
    }
    m.root(head.unwrap())
});
heap.collect();
let sum = heap.mutate(|m| {
    let mut sum = 0;
    let mut cur = Some(m.get(&list));
    while let Some(n) = cur {
        sum += n.value;
        cur = n.next;
    }
    sum
});
assert_eq!(sum, 999 * 1000 / 2);
}

What happens here:

  1. heap.mutate(|m| ...) enters the heap. m is a Mutator<'gc>, and every Gc<'gc, T> it hands out is tied to this one call by the 'gc brand.
  2. m.alloc(value) moves value into the heap and returns a Gc.
  3. m.root(gc) turns a Gc into a Root<NodeB>. A root carries no lifetime, so it can leave the closure, be stored anywhere and be sent to other threads.
  4. heap.collect() takes &mut Heap, so no mutate can be running. It marks from the roots and frees everything else.
  5. m.get(&root) brings the object back as a Gc in a new mutate.

Mutable edges

Gc fields are fixed once the object is built. A field that changes is a Slot:

#![allow(unused)]
fn main() {
use paragc::{Slot, Trace};

#[derive(Trace)]
struct Cell<'gc> {
    value: Slot<'gc, Node<'gc>>,
}

heap.mutate(|m| {
    let cell = m.alloc(Cell { value: None.into() });
    let node = m.alloc(Node { value: 1, next: None });
    cell.value.set(m, Some(node));        // the write barrier sees the Mutator
    assert_eq!(cell.value.get().map(|n| n.value), Some(1));
});
}

Slot::set takes the Mutator because the write barrier needs it. The barrier:

  • logs old-to-young edges for young collections;
  • keeps reference counts;
  • marks the overwritten value during concurrent marking.

Choosing a collection

CallUse it when
collect_if_needed()Between units of work. It decides between nothing, a young collection and a full one.
collect_young()You know most new objects are already garbage.
collect()You want everything unreachable gone now.
mark_concurrently() then finish_marking()Pauses must stay short while mutators keep running.
shrink()The program is idle and memory should go back to the system.

Threads

Heap is Sync. Wrap it in an Arc and call mutate from as many threads as you like. A collection (&mut self) waits until every one of them has left. Collector threads are a pool owned by the heap: they start at the first collection and park between collections.

Handles and brands

paragc’s handle types differ in how long they are valid and whether they keep their target alive.

HandleLifetimeKeeps aliveWhere it can live
Gc<'gc, T>one mutatewhile the mutate runs (no collection can start)locals, fields of heap objects
Slot<'gc, T>field of a heap objectyes, as an edgeinside heap objects
WordSlot<'gc>field of a heap objectyes, when the word is a pointerinside heap objects
Root<B>noneyesanywhere, any thread
Weak<B>nonenoanywhere, any thread
Far<'a, B>brand of the holder heapyes, registered in the target heapinside objects of the holder heap

Why brands

A Gc is a bare pointer (#[repr(transparent)] over NonNull<T>). It is only safe while no collection can move or free its target, which is exactly the duration of one mutate. The closure passed to mutate is generic over 'gc (for<'gc> FnOnce(&Mutator<'gc>) -> R), so:

  • a Gc<'gc, T> cannot be returned out of the closure, because R cannot name 'gc;
  • a Gc from one heap cannot be stored in another heap’s object, because the two brands differ.

brand! declares a type that maps a lifetime back onto a heap type:

#![allow(unused)]
fn main() {
brand!(NodeB = for<'gc> Node<'gc>);
}

Root<NodeB> stores no lifetime; m.get(&root) returns Gc<'gc, Node<'gc>> for the current mutate.

Raw pointers

Gc::as_ptr and Gc::from_raw convert to and from a raw data pointer taken in the same mutate, for NaN-boxing and similar tricks. The collector cannot see a raw address stored in an object. A type that stores raw addresses must:

  • report them in Trace::trace through Tracer::edge;
  • pass them to Tracer::relocate in Trace::relocate and write the new address back.

WordSlot covers the common case of a NaN-boxed 64-bit word (see Weak references and word slots).

Trace

#[derive(Trace)] generates:

  • trace, which reports every field that holds an edge;
  • relocate, which rewrites those fields after evacuation;
  • NO_EDGES, true when no field can hold an edge. Objects of such types are never pushed on the mark stack.

The derive refuses types that implement Drop. Destructors run in no particular order, so a Drop could see objects that were already destroyed. #[trace(unsafe_drop)] opts out when the destructor touches no Gc.

Heap types must be Send + Sync: objects are traced and dropped on collector threads.

Blocks, lines and headers

Sizes

ConstantValueMeaning
BLOCK32 KiBunit the heap hands out; aligned to its size
LINE256 Bunit of reuse inside a block (128 lines per block)
GRANULE8 Ballocation alignment; object sizes are whole granules
LARGE16 KiBobjects above half a block are allocated on their own
LARGE_MMAP64 KiBlarge objects from here up get their own mmap
HEADER24 Bprivate object header

Because blocks are aligned to 32 KiB, masking the low 15 bits of any object address gives its block.

The block header

Each block keeps, outside its data area:

  • line marks: one u32 epoch per line. A line is free when its mark is older than the last finished epoch, so clearing marks is never needed; a new collection just uses a newer epoch;
  • the object-start bitmap: one bit per granule, set at the first granule of every object. Sweeping and cross-heap lookups walk it to find objects;
  • a state (free, being allocated into, recyclable, full, swept) and counters used by evacuation.

An allocation buffer collects the start bits of the objects it allocates in one bitmap word and publishes them with a single atomic OR. It does that when it moves to another word, adopts another block, or when the mutate returns. Nobody reads those bits earlier: the buffer owns its blocks until the next collection.

Where blocks come from

On Linux:

  • each heap maps 2 MiB chunks itself and cuts them into aligned blocks;
  • a returned block first goes to a warm pool and keeps its memory, because the next round probably needs as many blocks;
  • only when the warm pool is full is the block madvise(MADV_DONTNEED)ed, giving its memory back; its address then goes to a cold pool for reuse. Warm blocks are handed out first;
  • the chunks are unmapped when the heap is dropped.

paragc bypasses glibc here: aligned allocations cost extra, and memory freed to glibc is not returned to the system.

On macOS, Windows and under Miri, blocks come from the global allocator.

The object header

A private object starts with a 24-byte Header:

FieldBitsMeaning
mark32epoch of the last collection that marked it; FORWARDED / BUSY bits during evacuation
info32size in granules (24 bits), reference count (6 bits), parity bit, large bit
visit64unsafe fn(*mut u8, &mut Tracer) for the type: traces or relocates its edges
drop64Option<unsafe fn(*mut u8)>, the destructor; after a move it holds the forwarding address

The first two words (Core) are shared with cross-heap objects, whose 16-byte PHeader has a type number and a birth stamp instead of function pointers. Blocks, lines, sweeping and marking therefore use the same code for both heaps.

A single object’s data can be at most 128 MiB (24 bits of granules).

Allocation

The thread-local buffer

Each thread in a mutate allocates through a Tlab: a cursor and a limit inside one block. An allocation that fits bumps the cursor and writes the header; nothing else is shared.

When the current run of free lines is too small, the buffer tries, in order:

  1. the next run of free lines in the same block (a line is free when its mark is older than the last finished epoch);
  2. a recyclable block, one that the last sweep found with free lines;
  3. an empty block;
  4. a new block from the segment pool.

Taking a block is one atomic operation on a lock-free list.

Overflow allocation

Objects larger than a line that do not fit the current run go to a second cursor, the overflow cursor (Immix overflow allocation). It looks at up to OVERFLOW_TRIES (8) available blocks for a run long enough, otherwise it opens a fresh block. The current run stays in place for small objects, so a medium object never throws away a good hole.

Large objects

An object above LARGE (16 KiB) is allocated on its own:

  • up to 64 KiB, from runs of blocks;
  • from 64 KiB, with its own mmap.

Large objects are never moved. Sweeping frees them whole.

Black allocation

During concurrent marking, a new object gets the current marking epoch, and its lines are marked as well. It is allocated “black”, so the marker never has to scan it. Its address goes to a list, so that its edges are counted at the end of marking.

Allocating with a tail

Mutator::alloc_tail(value, tail, fill) allocates an object followed by tail bytes of plain data:

  • the tail starts right after T (at size_of::<T>() from the data pointer), and fill writes all of it before the object can be reached;
  • the collector never looks inside the tail, but copies it with the object when the object moves or is promoted, because the header size covers it;
  • the type keeps the tail’s length itself.

j8 stores the bytes of every JS string this way. alloc_shared_tail is the same for shareable objects (see Promotion).

Buffers across collections

A buffer remembers the heap and the collection count it belongs to. After a collection it starts over, because the sweep may have reclassified its block.

Marking and the thread pool

Epochs

Marks are epochs, not bits. Each collection takes a new epoch number. An object is marked in this round when its mark word equals the current epoch, and a line is live when its mark is the last finished epoch. Nothing ever has to be cleared between collections.

Parallel marking

  1. The roots are spread over the workers.
  2. A worker reaching an object swaps the epoch into its mark word. Whoever swaps first owns the object. It marks the lines the object spans and pushes the object on its own deque. Types without edges (NO_EDGES) are never pushed.
  3. A worker pops an object and calls its visit function in tracing mode; each edge goes back to step 2.

Each worker has a crossbeam work-stealing deque. A worker that runs dry steals in batches from the others.

Termination. A worker whose deque is empty and that cannot steal counts itself idle and keeps trying. When every worker is idle at once, marking is complete.

Deep structures never touch the call stack: a million-node chain is a million deque pushes, not a million frames.

The pool

The pool starts at the first collection and lives as long as the heap.

  • A collection is handed out by bumping one atomic word that holds a generation number and the number of participants. Only that many workers are unparked.
  • Idle workers back off, then park.
  • A panic on a worker is caught and raised again on the thread that called the collection.

The tracer modes

The same visit function serves several purposes, selected by the Tracer:

ModeWhat visit does
tracingcalls Trace::trace; each edge is marked and pushed
relocatingcalls Trace::relocate; each edge is rewritten to its forwarding address
asking (cross-heap)answers whether the type is shareable and, if so, its type number in the cross-heap

The asking mode lets the collector learn about a type from the object alone, without a type registry in the private heap.

Sweeping

Sweeping turns the marks into free space and runs destructors.

The parallel sweep

Workers claim blocks in batches of 16. For each block, a worker:

  1. walks the object-start bitmap;
  2. for every object whose mark is not the current epoch, runs its destructor (unless it was moved; see Evacuation) and clears its start bit;
  3. classifies the block as empty, recyclable (some free lines) or full.

Empty blocks beyond what the last round used are returned to the system (MADV_DONTNEED); the rest stay as spares.

Destructors and threads

By default, destructors run in parallel on every collector thread. Heap::set_parallel_drop(false) runs them only on the thread that called the collection or sweep_concurrently. Finding the dead and recomputing lines stay parallel. Turn parallel drop off when destructors free memory that the mutator thread allocated: frees from other threads make the allocator contend.

Lazy and concurrent sweeping

finish_marking only finishes marking. It hands every block and large object to the sweeper and returns. From then on:

  • a mutator that needs a block first takes a swept one. Failing that, it claims an unswept block and sweeps it on the spot (lazy sweeping);
  • sweep_concurrently sweeps everything left on the pool and waits for blocks others are still sweeping.

Claiming is an atomic cursor, so each block is swept exactly once, by whoever claims it, before it is handed out. New objects carry the last finished epoch, so an allocation made during sweeping is never taken for dead.

collect is finish_marking followed by sweep_concurrently.

Shrinking

Heap::shrink, called when the program is idle:

  • runs a full collection;
  • keeps no empty blocks;
  • madvises away the whole pages of free lines inside recyclable blocks.

Live objects are untouched, and the freed lines can be allocated into again afterwards.

Concurrent marking and sweeping

With concurrent marking, the only pauses are a short handshake at the start and draining the grey queue at the end.

Start: the handshake

Heap::mark_concurrently(&self):

  1. finishes the previous sweep. The sweep judges objects by “mark ≠ that epoch”, so it must end before marking stamps live objects with a newer epoch;
  2. raises the request bit in the gate word. The top bit is the request; the low bits count threads inside mutate;
  3. waits until no mutator is inside. paragc does not scan stacks, so the snapshot must be taken while no mutator holds an unrooted Gc;
  4. marks the roots grey and drops the request.

Marking then runs on the pool while mutators continue.

During marking

  • Snapshot at the beginning. Writing a Slot marks the value it overwrites and pushes it to the heap’s grey queue. Every object reachable at the handshake is therefore found, even if a mutator unlinks it.
  • Black allocation. New objects get the marking epoch and their lines are marked.
  • Read barrier for weak references. upgrade marks and greys its target. Otherwise an object that was only weakly reachable at the snapshot could be taken out and stored under a black object, and be missed.
  • Line reuse. A line is free only when its mark is older than the last finished epoch, so lines that the marker has just stamped are never handed out.

End: the pause

finish_marking(&mut self) drains the grey queue in parallel, finishes reference counting (see below), clears dead weak references and hands the blocks to the sweeper. sweep_concurrently then sweeps while mutators run.

Recounting

Concurrent marking also rebuilds reference counts:

  • the handshake flips the count parity and drops the slots logged before it;
  • markers count every edge they scan;
  • a marker that recounts a slot rereads it afterwards, and logs it itself if a mutator wrote it in between;
  • objects allocated black are queued and their edges counted at the finish;
  • logged slots are then settled.

Counts are trusted again as soon as the finish returns.

Limits

  • Concurrent marking never moves objects, so mutators need no read barrier for moved objects.
  • Never call mark_concurrently from inside a mutate on the same heap: it would wait for itself to leave.
  • While a cross-heap is attached, concurrent marking is not supported.

Evacuation

A stop-the-world collection can move live objects out of sparse blocks while it marks: Immix’s opportunistic defragmentation. Marking, copying and rewriting edges are one pass.

Choosing blocks

  • Candidates: blocks that have not been allocated into since they were swept and that hold less than half a block of live data (EVACUATE_LIVE). They are taken sparsest first, at least 4, with no upper cap.
  • Copy targets: every other swept block.
  • Early full collections: collect_if_needed runs a full collection early once blocks exceed “live data + one round of allowed allocation” by 1.5×.

Copying

While marking, the first worker that reaches an object in a candidate block:

  1. claims it by setting BUSY in its mark word;
  2. copies it into its own copy buffer. The new copy is marked and gets its start bit and line marks;
  3. writes the forwarding address into the old header (the drop word) and sets FORWARDED.

Other workers that reach the old copy either wait for BUSY to clear or follow the forwarding address.

Rewriting edges

  • Every edge is rewritten through Trace::relocate.
  • Root slots are rewritten with a CAS, so a handle that another thread drops at the same time stays dropped.
  • Weak references follow moved targets.
  • The sweep clears the old copies’ start bits without running their destructors.

What is never moved

  • Large objects.
  • Anything during concurrent marking.
  • Targets of Far references from other heaps: their blocks drop out of evacuation before marking starts. See Far references.
  • Objects that young collections in SkipRemembered mode promote in place. See Young collections.

Consequence for users

Gc::as_ptr may differ from one mutate to the next. Code must not keep raw addresses across a collection, except through Trace::relocate.

Young collections

Most objects die young. Heap::collect_young traces only the objects allocated since the last collection.

Sticky mark bits

There is no separate nursery. An object marked with the last finished epoch is old; a new object starts with mark 0 and is young. A young collection marks with that same epoch:

  • an old object it reaches already carries the epoch, so the trace stops there;
  • a young object it reaches gets the epoch and becomes old (it is promoted).

The remembered set

An edge from an old object to a young one can only come from a Slot write. Outside concurrent marking, the write barrier logs the slot of an old object whenever the value written is young.

  • Slots of young objects are not logged: a young collection reaches them through the object itself.
  • During concurrent marking every new object is black and survives as old, so nothing is logged.
  • Every collection clears the log.

A young collection marks from the roots and from the logged slots. It sweeps only the blocks allocated into since their last sweep.

Moving survivors

Surviving young objects move into compact blocks. Heap::set_young_evacuation chooses how:

ModeBehaviour
SkipRemembered (default)Objects that an old object (a remembered slot) or another heap’s Far points at directly are promoted in place. The rest move; only young objects and roots point at them, and those are all relocated. Old objects are never written.
FullRemembered slots are rewritten too, so every young survivor can move. Use it only when old objects keep the address nowhere but in a Slot.
OffNothing moves; survivors are promoted in place.

A rule that follows from this

Young collections never scan old objects. A structure that indexes objects by address must itself be young while it points at young objects: when it changes, move it into a fresh object.

Scheduling

collect_if_needed runs young collections and a full collection every few rounds:

  • every 16 young collections while reference counts are trusted (YOUNG_PER_FULL_RC);
  • every 4 otherwise (YOUNG_PER_FULL).

With a cross-heap attached, young evacuation is forced to Full, because promotion moves every shareable survivor (see Promotion).

Reference counting

Old objects carry a small reference count. Most old garbage is freed by its count, in the background, and full tracing only runs every few rounds for cycles and overflowed counts. This follows LXR (Zhao, Blackburn & McKinley, 2022), stages one to three.

What is counted

RC(x) is the number of edges to x from old objects. Edges from a young object are counted when that object is promoted.

The count lives in the header’s info word:

  • 6 bits, which stick when they reach the maximum;
  • a parity bit. A stop-the-world full collection flips it and recounts every edge exactly while it marks; a count with the wrong parity is from the previous generation and starts again from 1.

Maintaining counts

A Slot is two words: the value, and the value it last counted.

  1. An old object’s slot is logged on its first write in a round.
  2. A young collection settles it: +1 for the new value, −1 for the value last counted.
  3. Roots are counted lazily (deferred root counting): +1 for each current root, −1 for the previous round’s roots.
  4. Decrements run after all increments.

An old object reaching zero:

  • has its edges decremented;
  • is finalized;
  • has its start bit cleared.

The lines of the affected blocks are then recomputed.

Background release

The pause (finish_young) only settles increments and pushes the decrements onto a queue. collect_young is finish_young + sweep_concurrently. On the pool:

  • workers pop decrements;
  • whoever brings a count to zero finalizes the object, clears its start bit, queues decrements for its edges and records the block as dirty;
  • objects at zero have no counted references, and every root and promoted young object was counted, so mutators cannot reach them.

Dirty blocks get their lines recomputed from the old objects left at the start of the next pause. Every collection first finishes pending decrements, so a recount never flips the parity under them.

Cycles and weak targets

  • Cycles never reach zero; the periodic full collection reclaims them.
  • An object with a weak reference gets a stuck count. Release runs in the background, too late to clear weak references first, so only tracing may free such an object.

Single worker

With one marking worker nobody else touches the counts, so the recount uses plain loads and stores instead of locked atomic read-modify-writes.

Weak references and word slots

Weak<B>

A Weak<B> is like a Root<B>: it has no lifetime and can be stored anywhere. Unlike a root, it does not keep its target alive.

#![allow(unused)]
fn main() {
let weak = heap.mutate(|m| m.weak::<NodeB>(m.alloc(Node { value: 1, next: None })));
heap.collect();
assert!(weak.is_cleared());
assert!(heap.mutate(|m| m.upgrade(&weak).is_none()));
}

How it works:

  • Each Weak owns a slot in the heap’s weak table, which is not a root set.
  • In every pause (full, young, the end of concurrent marking, group collections), after marking and evacuation and before sweeping, the table is walked:
    • a moved target gets its new address;
    • an unmarked target is cleared, by CAS, so that a handle dropped at the same moment is not revived.
  • During mutate, the table only points at live objects. Mutator::upgrade gives an Option<Gc>, and Weak::is_cleared works outside mutate.
  • Live targets of weak references get a stuck reference count (see Reference counting). A young object with only weak references is cleared by the next young collection, an old one by the next full collection.

Weak references can also be stored inside heap objects; they go with their holder.

WordSlot

A WordSlot<'gc> holds a u64 that the user encodes, such as a NaN-boxed JS value:

  • words at or above WORD_POINTER_MIN (0xFFF8 << 48) are pointers. Their low 48 bits are an object’s data address, and their top 16 bits are the user’s tag, kept as is through evacuation;
  • every other word is plain data.

WordSlot has the same barriers, counting and relocation as Slot. word_pointer decodes a word. A tagged word must point at a live object of the same heap.

Far references and group collection

Several private heaps can live in one process: one per isolate, one per subsystem. Far<'a, B> lets an object in one heap point straight at an object in another, with no copy and no indirection.

Creating and reading

#![allow(unused)]
fn main() {
// inside both heaps' mutate
let far = Far::new(&holder_m, &target_m, target_gc);
let holder = holder_m.alloc(Holder { far });
// later, reading needs the target heap's Mutator
let t = holder.far.get(&target_m);
}
  • A Far is branded with the holder heap, so it can only be stored in that heap’s objects.
  • Reading takes the target heap’s Mutator. Holding that mutator proves the target heap is open and that no collection of it is running.
  • A Far never changes. To point elsewhere, put it in an object behind a Slot and replace that object.

Entries: how the target heap sees it

Creating a Far claims a slot in the target heap’s root table, which also records the holder heap. Finalizing the object that holds the Far (by sweep or by reference count) returns the slot.

  • Collecting the target heap alone treats these entries as roots. Young collections, reference counting and concurrent marking need nothing new.
  • Entries are pinned. Before an evacuating collection marks anything, the blocks holding entry targets drop out of evacuation and become copy targets instead. A Far therefore never needs rewriting.

Cycles across heaps: collect_group

A cycle A → B → A survives collecting A alone and B alone, because each side is an entry root in the other. Heap::collect_group(&mut [&mut Heap]) (and CrossHeap::collect_group for cross-heaps) collects several heaps together:

  1. entries held from inside the group are not roots;
  2. each heap marks from its own roots;
  3. a traced Far hands its target to the target heap, seeded with that heap’s epoch;
  4. the heaps take turns until no heap has grey objects left;
  5. entries held inside the group whose target stayed unmarked belong to dead holders and are cleared, so a later collection never seeds a freed object.

Group collections do not evacuate.

Dropping order

Far holds an Arc of the target heap’s root table, so dropping the target heap first and the holder later is safe. Once the target heap is gone, its mutator cannot be obtained, so get can no longer be called.

Cross-heap overview

A cross-heap (CrossHeap) is a heap that lives in a shared-memory file. Every process that can open the file maps the heap and uses it: it can allocate, read, write and collect.

[dependencies]
paragc = { version = "0.6", features = ["crossheap"] }

The feature exists only on Linux. On macOS and Windows it compiles to nothing, and only the private heap is there. build.rs emits cfg(crossheap) when the feature is on and the target is Linux, and every cross-heap item is gated on that cfg.

Two kinds of heap, two scopes of sharing

shared between threadsshared between processes
private heap (Heap)✓✗
cross-heap (CrossHeap)✓✓, for every process that can open its file
From → toprivate heapcross-heap
private heap✓ direct pointer (Far between heaps)✓ CrossHeapRoot, or an absolute address once promoted
cross-heap✗ (other processes cannot see private memory)✓ CrossHeapSlot, CrossHeapRef, CrossHeapWeak

Because nothing in a cross-heap points into a private heap, private and cross-heaps never form cycles.

Pieces

PiecePage
Where heaps are mapped; the file layout; how the file grows and shrinksAddress space and file layout
Objects without code: #[derive(Shared)], type numbers, pointer maps, handlesObjects, types and pointer maps
Several processes in one heap; dying at any moment; heap numbers, owners, restartsProcesses, crashes and lifetime
References that never hold anything up; signatures another process can resolve; posting objects to the ownerWeak references, signatures and the mailbox
A cross-heap as the old generation of a private heapPromotion

Trust

Every process that maps a heap can read all of it and corrupt it. Processes that share a heap trust each other; the permission check is the file’s permission. A signature from an untrusted party is only read, though, and a forged one never crashes the reader.

The goal behind it

j8 runtimes in different processes exchange JS values without copying. A process sends a 32-byte signature; the receiver, or a broker such as dowin, maps the sender’s heap, finds the object and reads it, or passes the signature on.

Address space and file layout

The address region and windows

CrossHeapSpace::reserve takes a range of addresses, not memory (PROT_NONE + MAP_NORESERVE):

  • 64 windows × 16 GiB = 1 TiB, aligned to its own size;
  • cross-heap number k is always mapped at window k;
  • a process maps only the heaps it opened.

A pointer inside a cross-heap is an offset from the start of the region, so the same value names the same object in every process, even across heaps. The base is found from any address in the region by masking the low bits.

The fixed region

CrossHeapSpace::reserve_fixed reserves the region at FIXED_BASE = 64 TiB with MAP_FIXED_NOREPLACE. Every process that does so maps heap k at the same absolute address, so plain absolute pointers (Gc, Slot) inside cross-heap objects are valid everywhere. Promotion depends on this (see Promotion). A process can hold the fixed region only once at a time.

Inside a window

Every part sits at a fixed offset, so any process finds it without following a pointer:

offset 0      superblock (one page): identity, owner, counters, stack heads, the attachment table at 1024
              type table (1024 entries: type key → type number, pointer map position)
              pointer maps (64 K offsets)
              entry table (one entry per 16 KiB of window)
              block table (state of every block)
              blocks (32 KiB each, handed out from a cursor)

The superblock holds a magic number (paragcP5), the owner, a random incarnation, the persist and dead flags, the mailbox head, the mail count, the owner_only flag, and how far each part has been extended.

Starting empty, growing on use

  • A new heap’s file is one page long: only the superblock.
  • Every part is extended with fallocate when it is first used. fallocate only ever grows the file, so threads and processes can race on it safely.
  • On tmpfs, fallocate takes memory right away, so memory is used up to the file length. The rest of the window costs nothing.
  • A process entering mutate compares its mapped length with the superblock and maps more when needed: one comparison, no system call in the common case.

Giving memory back

Sweeping keeps empty blocks as spares, up to the amount allocated since the last collection. The rest are punched out:

  • file heaps: fallocate(PUNCH_HOLE | KEEP_SIZE);
  • anonymous heaps: madvise(MADV_REMOVE).

Runs of adjacent blocks are punched in one call. All-zero block metadata is a valid empty block, so punched blocks stay on the free stack and are reused like any other. CrossHeap::shrink keeps no spares.

Opening a heap

CallUse
space.create(path, threads)a new heap in a file; its number is claimed in the file’s directory
space.create_anonymous(threads)a new heap with no file (anonymous shared memory), usable only inside this process; for tests, Miri and an isolate’s own old generation
space.open(path, threads)an existing heap by path
space.open_fd(fd, threads)an existing heap from a file descriptor passed over a Unix socket (SCM_RIGHTS); no path needed
heap.fd()the descriptor to pass (file heaps only)

Objects, types and pointer maps

Objects in a cross-heap can be read and collected by processes that never linked the code of their type, so they carry no function pointers.

Shareable types: #[derive(Shared)]

#![allow(unused)]
fn main() {
use paragc::{CrossHeapSlot, Shared, cross_heap_brand};

#[repr(C)]
#[derive(Shared)]
struct Node<'p> {
    value: u64,
    next: CrossHeapSlot<'p, Node<'p>>,
}

cross_heap_brand!(NodeB = for<'p> Node<'p>);
}
  • #[repr(C)] is required, so the layout agrees across processes and binaries.
  • Fields may be plain data, CrossHeapSlot, CrossHeapRef, CrossHeapWeak, nested Shared types and fixed-size arrays. Promotion adds absolute-address edges: Gc, Option<Gc>, Slot, WordSlot.
  • No destructor: CrossHeapMutator::alloc checks it at compile time.
  • The derive generates a pointer map: the offset of every pointer field, through nested types and arrays.

The type table

The first allocation of a type registers it in the heap’s type table:

  • the type key is a hash of the type name, its size and its pointer map;
  • the entry records the type number, the size, and where the pointer map is stored.

A process that looks up a handle checks the type key, so a handle of the wrong type is refused rather than misread.

The header

A cross-heap object has a 16-byte PHeader:

FieldMeaning
mark, infothe same two words as a private header, so blocks, lines and sweeping are shared code
typethe type number
stampthe birth stamp (see Weak references and signatures)

Collection follows the pointer map of the type number; it never calls code.

Handles

HandleValidStores
CrossHeapGc<'p, T>inside one CrossHeap::mutatean absolute address in this mapping
CrossHeapSlot<'p, T>field of a cross-heap objectan offset from the region start, the same in every mapping
CrossHeapRoot<B>anywhere; in private heaps tooan entry number; holds the object alive
CrossHeapRef<'a, B>field of an object in heap A, pointing into heap Bthe target’s offset and B’s incarnation; registers an entry in B
CrossHeapWeak<B>anywhereone word: offset and stamp; holds nothing

get and set on a CrossHeapSlot take the CrossHeapMutator, which knows this mapping’s base address.

Entries

The entry table is the cross-heap’s root set. Each entry records the target’s offset and its holder:

  • an attachment slot, meaning a process;
  • HEAP_HOLDER | k, meaning another cross-heap;
  • 0, meaning nobody: a persistent root.

CrossHeapRoot::index is the entry number, valid in every mapping. CrossHeapMutator::find turns an entry number back into a handle after checking the type key; this is how another process picks up an object handed to it.

Large objects

Objects above 16 KiB take a run of fresh blocks. When such an object dies, its blocks become ordinary blocks again.

Collection

CrossHeap::collect:

  • marks in parallel from the entry table, reading each object’s pointer map, and sweeps in parallel;
  • never moves objects. Other processes hold offsets and weak words, which must stay valid;
  • keeps free blocks and free entries on lock-free stacks inside the file, with tagged heads against ABA.

Cross-heaps have no concurrent marking, young collections, reference counting or evacuation: collect is stop-the-world and waits for every live process’s mutators to leave.

Processes, crashes and lifetime

A process may be killed at any instruction, including in the middle of a collection. The rules on this page keep the heap readable and keep the other processes running.

The attachment table

Every mapping takes one of 32 slots in the superblock page (at offset 1024). A slot holds:

  • the process id;
  • the process start time, read from /proc/<pid>/stat. A reused pid is never mistaken for the old process, and zombies count as dead;
  • the number of its threads inside mutate;
  • the number of its threads waiting at the door.

The handshake

A collection request is one word holding the collector’s slot (0 means none).

  • A mutator increments its count and then checks the request.
  • A collector raises the request and then checks every count.
  • All of these are sequentially consistent, so at least one side sees the other.

Waiting is a futex on the shared word (not process-private). Waiters wake every 10 ms to check whether the other process is still alive. A collector that was waited on by stalled mutators lets them in before taking the next collection, so back-to-back collections cannot starve mutators.

Crash recovery

  • A dead mutator is not waited for. The next collector releases every entry its slot held and frees the slot, but never the slot that still owns the request: a newcomer reusing it would look like a live collector.
  • A dead collector is taken over by whoever sees the request owned by a dead process, a mutator at the door or another collector. The collection is redone from scratch with an epoch newer than the one the dead collector started, because its marks must not count for this round. Sweeping again is harmless, since it only ran after marking had finished.
  • Every step leaves the heap readable:
    • an object is written before its start bit (or a large object’s block kinds) is published;
    • a large object’s tail blocks are freed before its head, so an interrupted free is redone and skips the work already done;
    • the collector extends the block and entry tables up to their counters before reading them, in case a process died between bumping a counter and growing the file.

A process that dies may leave a few blocks or entries unusable (killed between taking one and recording it). Nothing it left is ever read as an object.

Owners and lifetime

A cross-heap belongs to the process that created it. The superblock records the owner (pid and start time) and a random incarnation.

  • When the owner exits or is killed, the heap dies with it unless CrossHeap::persist was called. Whoever notices first marks it dead and deletes the file and its marker. Memory goes back once every mapping is dropped.
  • Other processes see is_alive() == false, and try_mutate returns HeapDead. Their handles stay safe to use and to drop.
  • A CrossHeapRef stores its target heap’s incarnation. Once a dead heap’s number is reused, the reference reads None and collections do not follow it.
  • CrossHeapRoot::persist makes a root that belongs to no process. It is found again by entry number and returned with CrossHeapMutator::release.

Heap numbers

Numbers are claimed per directory through .paragc-<k> marker files. Every decision is taken under the marker’s flock, re-checked against the path after locking, so a half-created heap is never mistaken for a stale one and simultaneous creators get distinct numbers.

Several heaps at once: avoiding deadlock

Collectors and mutators take heaps like ordered locks:

  • a group collection takes each heap in heap-number order and drains it before taking the next;
  • CrossHeap::mutate_with enters two heaps lowest number first.

A mutator nesting in that order never waits on a heap that a collector holds while the collector waits on it. Nesting in the other order still works: a collector that cannot drain within 50 ms releases what it holds, pauses for a random, doubling interval (capped at 200 ms) and retries.

Who collects

Any attached process can call collect or collect_group, except on a heap marked owner-only. A cross-heap attached to a private heap as its old generation is owner-only (see Promotion).

Weak references, signatures and the mailbox

These three mechanisms carry a reference across processes without making any process wait for another.

Birth stamps

Every cross-heap object header has a 32-bit birth stamp: a SplitMix64 mix of the heap’s incarnation and the allocation epoch. Two objects that occupy the same address at different times almost certainly have different stamps.

CrossHeapWeak

A CrossHeapWeak<B> is one word: the object’s offset (in 8-byte units) in the high bits and its stamp in the low 27 bits.

  • It registers nothing in the target heap and keeps nothing alive.
  • No collection looks at it, so across processes it holds up no one.

Reading it inside the target heap’s mutate checks, in order:

  1. the block was opened, and its table entry has memory behind it;
  2. the start bit is set at that offset, or the offset is the start of a large object’s first block;
  3. the stamp matches.

If any check fails the result is None. This covers a dead object, a new object in the same place, and a heap number reused by a new heap. Stamps collide with a probability of about 2⁻²⁷.

Signatures

A Signature is 32 bytes: the weak word, the heap’s incarnation and the type key. It is the thing one process sends to another.

#![allow(unused)]
fn main() {
// sender
let sig: Signature = cross.mutate(|cm| cm.sign(obj));
let bytes: [u8; SIGNATURE_BYTES] = sig.into();
send(&bytes, cross.fd());                  // e.g. over a Unix socket with SCM_RIGHTS

// receiver
let sig = Signature::from(&bytes);
let heap = space.open_fd(fd, threads)?;
let value = heap.mutate(|cm| cm.resolve::<NodeB>(&sig).map(|n| n.value));
}
CallUse
sign(gc)sign an object in a cross-heap
sign_promoted(gc)sign a promoted object straight from a private Gc, with no brand
resolve::<B>(&sig)the object, if it is alive and of type B
verify(&sig)check a signature without knowing the type

A signature from an untrusted party is only read. A forged or stale one gives None and never crashes the reader.

The mailbox: the owner acts for others

Some resources cannot be shared: file descriptors, Boxes, anything private to the owner’s process. Another process asks the owner to act instead:

  1. CrossHeapMutator::post(obj) takes an entry owned by no process, so the request survives the poster’s death;
  2. it pushes the entry on the mailbox stack in the superblock;
  3. it bumps the mail count, a futex word, and wakes the owner.

The owner polls CrossHeap::mail(), the count received so far, or sleeps in wait_mail(seen, timeout) until it changes. It must not wait inside the heap’s own mutate, or collections would wait for it forever. take_mail takes everything, oldest first; find gets each object, and release returns its entry when done.

Shrinking and descriptors

CrossHeap::shrink runs a collection that keeps no spare blocks, which brings the file’s real usage down after a burst of garbage. CrossHeap::fd gives the file descriptor to pass to another process. The receiver needs no path, and the heap is mapped at the same window number in every process.

Promotion: a cross-heap as the old generation

Allocating every shareable object directly in a cross-heap would mean deciding at allocation time which heap an object goes to. Promotion avoids that. Objects are allocated in the private heap as usual, and those that survive a young collection move into a cross-heap attached as the old generation. Allocation stays lazy, and short-lived objects never touch shared memory.

Setting it up

#![allow(unused)]
fn main() {
let space = CrossHeapSpace::reserve_fixed()?;          // the fixed region, at 64 TiB
let cross = space.create(path, threads)?;              // or create_anonymous for in-process use
let mut heap = Heap::new(threads);
heap.attach_cross_heap(&cross)?;
}
  • The cross-heap must be in the fixed region, so absolute addresses stored in its objects are valid in every process that also reserved it.
  • The cross-heap becomes owner-only: other processes and collect_group leave it alone. Only this private heap collects it.
  • With a cross-heap attached, young evacuation is forced to Full, and concurrent marking is not supported.

Shareable private objects

#![allow(unused)]
fn main() {
#[repr(C)]
#[derive(Trace, Shared)]
struct Node<'gc> {
    value: u64,
    next: Slot<'gc, Node<'gc>>,
}

heap.mutate(|m| m.alloc_shared(Node { value: 1, next: None.into() }));
}

Mutator::alloc_shared (and alloc_shared_tail) takes a type that is both Trace and Shared, without Drop. Its Gc, Option<Gc>, Slot and WordSlot fields are recorded in the pointer map as absolute-address edges (WORD_EDGE, PTR_EDGE).

What a young collection does

When a worker reaches a young object during a young collection:

  1. it asks the object’s visit function, in asking mode, whether the type is shareable and what its type number in the cross-heap is. The type is registered there on first use;
  2. if the type is shareable, the worker claims the object, copies it with its own promotion buffer into the cross-heap, writes the PHeader (type number and birth stamp), and forwards the old header to the new place;
  3. slots, roots and weak references in the private heap are relocated to the new address, as for any move.

A promoted object’s edges are traced too. Its targets must be shareable; a non-shareable target reached from a promoted object panics (in_shared).

The private heap skips cross-heap addresses everywhere: marking, reference counting, the remembered set, the write barrier, root and weak tables.

Writing a private object into a cross-heap object

A cross-heap object can be written after promotion, for example promoted.next.set(m, Some(fresh)) where fresh is still young. The barrier:

  • records the slot in the remembered set;
  • sets promotion_pending.

Until the next young collection, the slot holds a private address. Other processes treat an address outside the region as empty. The next young collection promotes fresh and rewrites the slot through the remembered set. A host checks Heap::promotion_pending() when a unit of work ends and runs a young collection if it is set.

Collecting

Heap::collect:

  1. runs a young collection, so every shareable survivor is promoted;
  2. runs a full private mark;
  3. collects the cross-heap with extra roots: the cross-heap edges the private mark found, and the root-table entries pointing into the cross-heap;
  4. clears private weak references whose cross-heap target died.

CrossHeap::collect on an owner-only heap does nothing.

Handing an object to another process

#![allow(unused)]
fn main() {
let sig = heap.mutate(|m| cross.mutate(|cm| cm.sign_promoted(m.get(&root))));
}

sign_promoted returns None for an object that is still private. A signature keeps nothing alive. If the owner drops the object and collects, the signature resolves to None.

How j8 uses it

With j8’s crossheap feature, an Isolate takes a cross-heap (attach_cross_heap):

  • scope.shares.share(mc, gc) records an object to share and returns a ticket;
  • j8 never collects in the middle of running JS. At the end of Isolate::enter, if anything is pending, it runs one young collection and then signs the recorded objects;
  • take_signatures hands out (ticket, signature) pairs.

JS strings are shareable: their bytes, and the UTF-16 units of non-ASCII text, live in the object’s tail.

Testing and Miri

Test files

FileCovers
tests/gc.rsthe private heap: survival, finalization counts, threads, large objects, deep structures, concurrent marking and sweeping, evacuation, young collections, reference counting, shrinking, serial drop
tests/weak.rsweak references through every kind of collection, the read barrier during concurrent marking
tests/word.rsWordSlot through full, young and concurrent collections
tests/far.rsFar, pinning, group collections, cross-heap cycles of private heaps
tests/cross_heap.rscross-heaps in one process: pointer maps, large objects, two mappings, CrossHeapRef, group collections, weak references, signatures, mailbox, shrink, promotion, tails (needs --features crossheap)
tests/processes.rsseveral processes on one heap: killed mutators, killed collectors, random kills, restarts, heap numbers, 8 processes with half killed (needs --features crossheap)

The README’s verification table lists every test and what it checks.

Running them

cargo test --test gc -- --exact <name>
cargo test --features crossheap --test cross_heap
cargo test --features crossheap --test processes

promotion_into_attached_cross_heap runs several scenarios inside one test, because a process can hold the fixed region only once at a time and tests in one file run on parallel threads.

Miri

Every test also runs under Miri, with both Stacked Borrows and Tree Borrows (scaled down under cfg(miri)):

MIRIFLAGS="-Zmiri-permissive-provenance -Zmiri-ignore-leaks" cargo +nightly miri test --test gc -- --exact <name>
MIRIFLAGS="-Zmiri-permissive-provenance -Zmiri-ignore-leaks -Zmiri-tree-borrows" cargo +nightly miri test --test gc -- --exact <name>
  • Miri cannot map files. Under Miri the cross-heap region is an ordinary allocation (4 windows of 16 MiB); the tests without a file run on it, and the file tests are skipped.
  • -Zmiri-ignore-leaks is needed because crossbeam-epoch’s global collector still holds deferred garbage at exit.
  • At 4 collector threads Stacked Borrows reports a violation inside crossbeam-epoch itself, so tests use 2 under Miri. A few concurrent tests still hit it under Stacked Borrows and are clean under Tree Borrows.

Known flaky test

gc::background_release_while_mutating can fail in release builds; it passes in debug builds. The failure predates 0.6.0.

Benchmarks

paragc against cppgc (V8’s Oilpan), gc-arena, gc (rust-gc) and dumpster on a 16-core machine. The numbers are wall-clock milliseconds, best of 5. Setup, workloads and every configuration are in benches/benchmark.md.

paragccppgcgc-arenadumpstergc
Pause, 1M live + 1M dead, 1 thread20.244.216.316.390.2
Pause, 16 threads4.244.9–––
Pause, concurrent marking + sweeping, 1 thread0.02––––
GCBench, 1 thread50.3121.0118.097.8294.6
GCBench, 4 threads54.394.2–––
Many mutators, 16 threads9.0––343.5–
Fragmentation (~80 MB live), RSS after / peak MB111 / 416445 / 1894–––

How to read them:

  • On a single thread, gc-arena and dumpster pause for less time. paragc’s full collection also rebuilds reference counts.
  • With threads, and in throughput, paragc leads.
  • cppgc’s forced full collection marks on one thread even with every parallel flag on, and pays an FFI call per allocation and per edge in this harness.

The comparison benchmarks depend on large libraries such as V8, so benches/ is a workspace of its own.

Code conventions

No locks

paragc takes no locks, not even inside collections. Shared state changes through atomics, lock-free stacks with tagged heads, append-only segmented vectors and futex waits. The work-stealing deques and backoff come from crossbeam; the append-only vector and the push-only list are paragc’s own (src/sync.rs).

Exclusion by borrowing

Operations that need the world stopped take &mut Heap. The borrow checker is the safepoint protocol. New code should keep it that way rather than add runtime coordination for private heaps.

Source layout

The source is flat; similar things live together:

FileContents
layout.rsblocks, lines, headers, the cross-heap window layout and superblock
heap.rsHeap, Mutator, Tlab, collections, CrossHeap, CrossHeapMutator, promotion
mark.rsTracer, the work-stealing crew, the copier, the cross-heap marker
sweep.rssweeping and large objects
handle.rsGc, Slot, WordSlot, Root, Weak, Far, cross-heap handles, Signature, Shared
shm.rsthe cross-heap address region, windows, heap numbers, process liveness (Linux)
sync.rslock-free building blocks and futex waits

Cross-heap items are gated on cfg(crossheap), set by build.rs only on Linux with the crossheap feature.

Style

  • Code, comments, messages and docs in English; READMEs in English (default) and Chinese.
  • cargo clippy --all-targets is clean with pedantic, with and without --features crossheap.
  • Named constants, never bare numbers, for sizes, thresholds and bit fields.
  • Every unsafe block states its safety argument in a // SAFETY: comment.

Releases

The repository’s main is protected: every change goes through a pull request on GitHub (0x00-Community/paragc). Versions are published to crates.io (paragc and paragc-macros, same version) and tagged vX.Y.Z.

Limits and open problems

This page lists what paragc does not do yet and the places where its design is under strain. Read it before relying on cross-heaps.

The private heap

  • No stack scanning. Every object that must survive a collection is reachable from a Root, Far or entry.
  • 128 MiB per object. The header stores the size in 24 bits of granules.
  • Slot is two words: the value and the value last counted for reference counting.
  • Concurrent young collections do not exist. A young collection is a pause, short as it is.
  • Address-indexed structures must stay young while they point at young objects (see Young collections).
  • One flaky test: gc::background_release_while_mutating in release builds.

Cross-heaps

  • Stop-the-world only. A cross-heap has no concurrent marking, young collections, reference counting or evacuation. collect waits for every live process’s mutators to leave, so a process that is alive but stuck inside mutate stalls collection. Only dead processes are skipped.
  • No compaction. Cross-heap objects never move, so fragmentation is only reduced by reusing lines and punching empty blocks.
  • 64 windows. Heap numbers are window numbers in a 1 TiB region, so one directory holds at most 64 live cross-heaps, and every heap is at most 16 GiB.
  • CrossHeapRef registrations are only returned by group collections. Code that rewrites them often should run group collections.
  • Trust. Every process that maps a heap can read and corrupt all of it. There is no per-object protection and no locking. Concurrent writers from several processes get no consistency guarantees; this is a deliberate choice, with thread semantics expected to come from the language above.
  • Dead processes can leave a few blocks or entries unusable, if they were killed between taking one and recording it.
  • Stamps collide with probability about 2⁻²⁷, so a stale weak reference or signature can very rarely resolve to a new object of the same type at the same address.

Promotion

  • The fixed region is per process. reserve_fixed maps 1 TiB at 64 TiB with MAP_FIXED_NOREPLACE. If something else already sits there, it fails, and a process can hold it only once.
  • Concurrent marking is off while a cross-heap is attached, and young evacuation is forced to Full. A runtime that promotes gives up paragc’s shortest pauses.
  • Promotion panics on a non-shareable edge. A shareable object that reaches a non-shareable one through a traced edge makes the collector panic. That is a programming error, but it surfaces in the collector rather than at the write.
  • The owner-only cross-heap grows until a full collection. Young collections promote into it but never free in it. Only Heap::collect reclaims cross-heap garbage, so a runtime that mostly runs young collections must still schedule full ones.
  • Anonymous cross-heaps are private. create_anonymous is visible only inside its process. A runtime that wants other processes to read its objects must create a file heap and pass its descriptor.
  • A short window of invisibility. A private object written into a cross-heap slot stays private, and reads as empty elsewhere, until the next young collection.

The object model above paragc (j8)

Sharing a JS value means the receiver must understand the object’s layout, not just its bytes. In j8 today:

Part of a JS objectWhere it livesShareable
stringsGC heap, bytes in the object’s tail✓ (since j8 #49)
shapes (property names, attributes, transitions)Arc<Shape> outside the heap; objects keep a raw *const Shape✗
property values (inline slots, the store)GC heaponly once their shape is shareable
dictionary-mode propertiesGC objects holding Vec and HashMap✗
functionsbytecode and FunctionInfo outside the heap✗
host objectsBox<dyn Any>✗; the owner acts for others through the mailbox

Shapes are the hard part. Shape identity is a memory address:

  • the executor’s inline caches compare shape addresses and keep Arc<Shape> to stay valid;
  • the JIT bakes shape addresses into machine code (CheckShape).

A shape that is an ordinary moving GC object would break both. The candidate designs:

  1. Immortal shapes in a fixed place. Shapes live in an append-only area inside the fixed region, never move and are never freed. Caches and the JIT stay as they are, and Arc refcounting goes away. The cost is that shape memory only grows; objects with more than 64 properties already switch to dictionary mode.
  2. Shapes as moving GC objects. Memory is reclaimed, but inline caches must hold traced references and the JIT must either stop baking addresses or recompile when shapes move.
  3. A second, shareable description made at promotion. The hot path is unchanged, but every object carries one more word, and later property additions must be kept in sync on both sides.

This decision is open; it blocks stage 3 of cross-process objects in j8.

Roadmap

Done

VersionWhat
up to 0.4parallel stop-the-world collection and a persistent pool; concurrent marking; concurrent and lazy sweeping; opportunistic evacuation; young collections; reference counting with background release; tracing every 16 young collections; concurrent recount; Far and group collections
0.5cross-heaps on shared memory with several processes and crash recovery; CrossHeapRef and group collections across cross-heaps; heap numbers and restarts; heap lifetime tied to the owner; WordSlot and Weak
0.6.0the crossheap feature (Linux only); the Public* API renamed to CrossHeap*; CrossHeapWeak, birth stamps and signatures; open_fd; the mailbox; shrinking cross-heaps; promotion into an attached cross-heap with owner-only collection; deferred promotion of private objects written into cross-heap slots; sign_promoted
0.6.1alloc_tail / alloc_shared_tail

Next

  • Cross-process JS objects in j8, stage by stage:
    1. an isolate takes a cross-heap and signs shared objects when a turn ends (done);
    2. strings in the GC heap (done);
    3. shapes: see Limits and open problems;
    4. ordinary objects and arrays;
    5. functions, with bytecode in the cross-heap;
    6. host objects, through the owner and the mailbox.
  • Cross-heaps with concurrent marking, young collections and reference counting, so a large shared old generation does not mean long pauses.
  • Concurrent marking with a cross-heap attached.
  • A concurrent young collection, and a one-word Slot.

Glossary

TermMeaning
block32 KiB aligned unit of heap memory
line256 B unit of reuse inside a block
granule8 B, the allocation alignment
epochthe number a collection writes into mark words and line marks; never cleared
mutateHeap::mutate, a call during which the thread may allocate and use Gc handles
brandthe 'gc lifetime tying a Gc to one mutate; also the brand! type mapping it back
rootRoot<B>, a handle with no lifetime that keeps its object alive
entrya root-table slot claimed for a reference from outside the heap (Far, cross-heap entries)
tlabthread-local allocation buffer
overflow cursorsecond allocation cursor for medium objects that do not fit the current run
black allocationgiving new objects the marking epoch during concurrent marking
SATBsnapshot at the beginning: the write barrier marks overwritten values during concurrent marking
evacuationcopying live objects out of sparse blocks while marking
forwarding addressthe new address left in an old header after a move
young / oldnot yet / already marked with the last finished epoch (sticky mark bits)
remembered setslots of old objects that were written with young values
promotiona young object becoming old: in place, by move, or into an attached cross-heap
RCreference count of edges from old objects
paritythe bit that tells current counts from the previous generation’s
Fara direct reference from one private heap into another
group collectioncollecting several heaps together to reclaim cycles across them
cross-heapa heap in a shared-memory file, usable by several processes
region / windowthe reserved address range for cross-heaps / one heap’s 16 GiB slice of it
fixed regionthe region at 64 TiB, the same address in every process
superblockthe first page of a cross-heap
attachmenta process’s slot in a cross-heap’s superblock
incarnationa random identity a cross-heap gets at creation
birth stamp32-bit tag in a cross-heap header from the incarnation and the allocation epoch
type keyhash of a shareable type’s name, size and pointer map
pointer mapoffsets of the pointer fields of a shareable type
signature32 bytes (weak word, incarnation, type key) that identify a cross-heap object to another process
owner-onlya cross-heap only its owner may collect (an attached old generation)
mailboxa stack in the superblock where other processes post objects for the owner to act on