Runtime support: garbage collectors, JIT compilers and virtual machines
Overview of runtime support: how garbage collectors, JIT compilers and virtual machines manage memory, execution and trade-offs in high-level language runtimes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Many modern languages (Java, C#, JavaScript, managed C++) run on a runtime system that gives services like memory management and dynamic compilation. An engineer uses these concepts when designing language runtimes, writing performance-critical libraries, debugging memory/performance problems, or building system software that interacts with managed runtimes (for example: device drivers, hypervisors, or native libraries). Clear understanding helps you reason about latency (pause times), throughput, memory use and correctness of programs that do not manage memory manually.
Key ideas
All bolded words are defined the first time they appear.
Virtual machine (VM): an abstract software layer that provides an execution environment for programs. It often defines an instruction set (bytecode), execution rules, and runtime services. Two main categories: system VM (implements an entire OS abstraction) and process VM (runs a single program or process; e.g., the JVM). Draw: a rectangle labelled "Process" containing a smaller rectangle labelled "VM"; below VM draw boxes: "class loader", "bytecode verifier", "interpreter", "JIT", "GC", "native interface".
Bytecode: a compact, platform-neutral instruction sequence executed by the VM's interpreter or compiled by a JIT.
Just-In-Time (JIT) compiler: a compiler that translates bytecode or intermediate representation to native machine code at runtime, typically for methods or hot code paths. JITs trade compile time and memory for faster execution.
- Tiered compilation: using multiple compilation levels (fast low-optimization first, then higher optimization for hot code). Example: baseline interpreter → fast JIT (less optimization) → optimized JIT (heavy optimization). Draw: a pipeline with arrows showing promotion based on a hotness counter.
- On-Stack Replacement (OSR): replacing currently executing interpreted frames with compiled frames mid-execution to allow long-running loops to be optimized without restarting.
- Inline caching: a technique to speed up dynamic dispatch by caching call target(s) at a call site; transitions: monomorphic → polymorphic → megamorphic.
Garbage collector (GC): runtime system component that automatically reclaims memory belonging to objects the program can no longer reach.
Formal correctness properties (state precisely as you would on an exam):
Safety (no-loss): A garbage collector is correct with respect to safety if: "No object that is reachable from the program's root set is reclaimed". Assumption: reachability defined by following pointers from root set.
Liveness (eventual collection): A garbage collector is correct with respect to liveness if: "Every object that is not reachable will eventually be reclaimed", assuming the program does not create new references that make it reachable again.
Root set: the set of references directly accessible by the program (stack variables, CPU registers, global/static variables, and VM internal references). In precise collectors, roots and pointers are identified exactly; conservative collectors (common with unmanaged languages like C/C++) may treat non-pointers that look like addresses as roots, which can retain garbage.
Reachability: an object is reachable if there exists a path of references from any root to that object.
GC families and their defining invariants:
- Reference counting: each object stores a counter of incoming references. Invariant: counter equals the number of pointers to the object (from roots and heap), excluding temporary/runtime bookkeeping. Main property: immediate reclamation when count drops to zero. Weakness: cannot detect cyclic garbage. Draw: small objects A→B→A with counters and show counters never reach zero.
- Tracing collectors (e.g., mark-sweep, copying): they discover reachable objects by tracing from roots and reclaim the rest. Incremental/concurrent tracers maintain a tri-color invariant (white/grey/black) and use write barriers (e.g., snapshot-at-the-beginning or incremental update) to ensure no reachable object is missed while the mutator runs.
- Mark-Sweep: two phases: mark (trace reachable, set mark bit), sweep (traverse heap and free unmarked objects). Invariant: after mark, all reachable objects are marked.
- Copying collector: divide heap into from-space and to-space; copy reachable objects to to-space and leave forwarding pointers in from-space. Invariant: after copy, all reachable objects are in to-space and references updated to point to new copies.
- Generational collectors: partition heap by object age (young/old generations). Empirical basis: generational hypothesis — most objects die young. So collect young generation frequently and old generation less often. Requires a write barrier: when an old object gains a pointer to a young object, record it (remembered set, often via card marking) so young-heap collections know roots in old generation.
Performance trade-offs:
- Throughput: fraction of time spent doing mutator (application) work vs GC. Higher throughput favors less frequent, longer GC pauses.
- Pause time (latency): time the application pauses for a stop-the-world operation or blocking GC. Real-time and interactive systems favor low pause times. Collectors are categorized as stop-the-world, incremental, or concurrent; the latter two reduce pause times by interleaving GC work with the mutator.
- Space overhead: extra memory needed for GC metadata (mark bits, forwarding pointers), plus costs from fragmentation in non-moving collectors or reserved 'to-space' in copying collectors.
Interaction of JIT and GC: JITted code must allow object relocation by GC and cooperate (emit and obey write/read barriers). The VM must maintain correct metadata (stack maps, object layouts) so GC can find roots in compiled frames. Collections and deoptimization occur at safepoints; stack maps at safepoints precisely enumerate live references in compiled frames.
Connections to other course topics: JVM class loading and verification relate to Programming language grammars and Syntax-directed translation; Code generation and storage allocation are relevant when JIT emits machine code; Linkers and dynamic linking concepts appear when JIT links method calls.
Formulas
Heap_live = Σ size(obj) for all reachable objects — Heap_live: bytes of live data.
Heap_free = Heap_capacity - Heap_live — free bytes before allocation fail (idealized). In non-moving heaps, fragmentation may reduce usable free space; in copying collectors you must also reserve sufficient to-space.
Pause_time ≈ k · n_scanned — Pause time proportional to number of scanned objects (k depends on machine and implementation). Verify k experimentally; used for rough reasoning about pauses.
Throughput = 1 - (GC_time / Total_time) — fraction of time spent outside GC.
Syntax to remember (bytecode-like):
new <class> — allocate a new object
invokevirtual <method> — dynamic method call
aload <i> / astore <i> — load/store reference from local slot i
Worked examples
- Mark-Sweep trace (exam-style): Given: Heap contains objects A(size 16), B(8), C(12), D(4). References: Root r1 → A; A → B; B → C; C → B (cycle); D is unreferenced. Steps:
- Mark phase: start from r1: mark A, then B, then C. B and C form a cycle but are reachable and marked. D is not reached.
- Sweep phase: scan heap entries: free any unmarked objects. D is freed; A,B,C remain. Final: Free list includes D(4). Answer: Objects A,B,C live; D reclaimed.
Reference counting cycle example: Objects: X and Y; X->Y and Y->X; a root initially points to X. After the program drops all root pointers to X and Y, each object still has reference count 1 due to the mutual pointers, so neither count reaches zero and neither object is reclaimed. Result: memory leak. Cycle collector fix (high level): detect objects unreachable from roots by doing a trial decrement phase: recursively decrement internal reference counts in candidate set and reclaim those with resulting zero counts. Example shows detection steps and final reclamation.
JIT tiering example (trace of hotness counters): Method M invoked 1) first execution by interpreter (count=1..1000); 2) after count hits threshold 1000, VM invokes fast JIT to compile M to baseline native code; 3) if M still hot and has heavy loops, after threshold 10000 VM recompiles with aggressive optimizations and inlining. Show state transitions: Interpreter → Baseline JIT (monomorphic inline cache) → Optimized JIT (inlined call sites, OSR used for hot loops). Final answer: explain why repeated execution benefits performance once compilation cost is amortized.
Common mistakes
- Forgetting the write barrier cost and role in generational/incremental collectors.
- Mixing up interpreter/JIT roles: interpreter provides portability and low compile cost; JIT trades time for speed later.
- Thinking copying collectors never need free lists: purely copying young generations typically use bump-pointer allocation, but many real systems also include non-moving regions (e.g., old or large-object spaces) that are managed with free lists or region free sets.
For your exam
Types of questions you will get:
- Definitions and short notes (define VM, GC, JIT, generational hypothesis, root set).
- Diagrams (draw mark-sweep phases; draw generational heap with pointers and write barrier cards; draw tiered compilation pipeline).
- Derivations/arguments (prove safety of tracing collector: any reachable object will be marked if trace follows all pointers from roots; show why reference counting cannot collect cycles).
- Algorithms (write pseudo-code for mark phase, sweep phase, or reference counting updates and describe complexity).
- Short programs/traces (given a heap graph, show mark and sweep results or simulate reference-count updates).
What a full-marks answer includes:
- Clear definitions (bold term and concise formal property), assumptions stated (e.g., how roots are defined), step-by-step algorithms/pseudocode, diagram with labels when asked, and a final conclusion or justification of correctness (safety/liveness) and complexity (time/space). Mention any practical trade-offs.
Quick check
- What is the root set in GC?
- Why can't simple reference counting collect cycles?
- What is the main purpose of a JIT compiler? Answers: The root set is the set of references directly accessible by the program (stack, registers, globals); Reference counting fails on cycles because objects in a cycle can have non-zero counts even when unreachable; A JIT compiler translates bytecode to native code at runtime to improve execution speed of hot code paths.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?