Memory Lab · simulation 5 of 5
Reachability, garbage collection and RAII
Mark everything the roots can reach, sweep the rest, and compare with cleanup that happens at a known point: using, try-with-resources, with and destructors.
The full explanation is in the lesson Reachability, garbage collection and RAII.
What to watch for
- Marking follows references from the roots; an already-marked object is skipped, which is why cycles terminate.
- An unreachable cycle is reclaimed by a tracing collector, needs CPython’s cycle collector, and leaks with shared_ptr.
- Turn on the scoped resource: it is closed before any collection, deterministically.
In each language
- C#
- Tracing, generational GC; using/Dispose for deterministic cleanup.
- Python
- CPython: reference counting plus a cycle collector; with-blocks for cleanup.
- Java
- Tracing GC (several collectors); try-with-resources for cleanup.
- C++
- No GC: owners, destructors (RAII), unique_ptr and shared_ptr; weak_ptr breaks cycles.
The programs
Mark and sweep in four languages against one shared fixture of object graphs (cycles, no roots, shared targets, self-references), plus deterministic cleanup (using, with, try-with-resources, RAII), CPython freeing a cycle only after gc.collect(), and a weak_ptr back link in C++.
namespace Bekadan.Dsa.Examples.Memory;
/// <summary>
/// Garbage is decided by reachability from roots. Collect runs the mark-and-sweep idea
/// on a small object graph (the .NET GC is far more elaborate: generational, compacting,
/// and it decides when to run). DeterministicCleanup shows that releasing a resource is a
/// separate matter: using calls Dispose at a known point.
/// </summary>
public static class Reachability
{
public static (List<string> Reachable, List<string> Garbage) Collect(
IReadOnlyList<string> objects, IReadOnlyList<(string From, string To)> references, IReadOnlyList<string> roots)
{
var refs = references.ToLookup(r => r.From, r => r.To);
var marked = new HashSet<string>();
var work = new Stack<string>();
foreach (var root in roots)
{
if (marked.Add(root)) work.Push(root);
}
while (work.Count > 0)
{
var current = work.Pop();
foreach (var target in refs[current])
{
if (marked.Add(target)) work.Push(target); // already marked: skip (this is what ends cycles)
}
}
var reachable = new List<string>();
var garbage = new List<string>();
foreach (var obj in objects)
{
if (marked.Contains(obj))
{
reachable.Add(obj);
}
else
{
garbage.Add(obj); // a tracing GC reclaims it, cycles included
}
}
return (reachable, garbage);
}
public sealed class TrackedResource(string name, List<string> log) : IDisposable
{
public void Use() => log.Add($"use {name}");
public void Dispose() => log.Add($"dispose {name}");
}
public static List<string> DeterministicCleanup()
{
var log = new List<string>();
using (var file = new TrackedResource("file", log))
{
file.Use();
} // Dispose runs here, whatever the GC does
log.Add("after using");
Check(log.SequenceEqual(["use file", "dispose file", "after using"]), "Dispose runs at the end of the using block");
return log;
}
private static void Check(bool condition, string claim)
{
if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/Reachability.cs
"""Reachability decides garbage; with-blocks decide when resources are released.
CPython frees most objects when their reference count drops to zero; objects in
unreachable cycles wait for the cyclic garbage collector (the gc module). The
mark-and-sweep below shows the reachability rule itself.
"""
import gc
import weakref
from types import TracebackType
def _check(condition: bool, claim: str) -> None:
if not condition:
raise AssertionError(f"Claim failed: {claim}")
def collect(objects: list[str], references: list[tuple[str, str]], roots: list[str]) -> tuple[list[str], list[str]]:
refs: dict[str, list[str]] = {}
for source, target in references:
refs.setdefault(source, []).append(target)
marked: set[str] = set()
work: list[str] = []
for root in roots:
if root not in marked:
marked.add(root)
work.append(root)
while work:
current = work.pop()
for target in refs.get(current, []):
if target not in marked: # already marked: skip (this is what ends cycles)
marked.add(target)
work.append(target)
reachable: list[str] = []
garbage: list[str] = []
for obj in objects:
if obj in marked:
reachable.append(obj)
else:
garbage.append(obj)
return reachable, garbage
class TrackedResource:
def __init__(self, name: str, log: list[str]) -> None:
self.name = name
self.log = log
def __enter__(self) -> "TrackedResource":
return self
def __exit__(self, kind: type[BaseException] | None, error: BaseException | None, trace: TracebackType | None) -> None:
self.log.append(f"exit {self.name}")
def use(self) -> None:
self.log.append(f"use {self.name}")
def deterministic_cleanup() -> list[str]:
log: list[str] = []
with TrackedResource("file", log) as file: # __exit__ runs the moment this block ends
file.use()
log.append("after with")
_check(log == ["use file", "exit file", "after with"], "__exit__ runs at the end of the with-block")
return log
class Node:
def __init__(self) -> None:
self.other: "Node | None" = None
def cycle_needs_the_collector() -> tuple[bool, bool]:
"""(alive after the last name is deleted, freed after gc.collect()) for a two-object cycle."""
gc.disable()
try:
a, b = Node(), Node()
a.other, b.other = b, a
probe = weakref.ref(a)
del a, b
alive = probe() is not None # each still has a reference count of 1, from the other
gc.collect()
return alive, probe() is None
finally:
gc.enable()
Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_reachability.py
package dev.bekadan.dsa.memory;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Garbage is decided by reachability from roots. collect runs the mark-and-sweep idea
* on a small object graph (real JVM collectors are generational and concurrent, and
* choose when to run). deterministicCleanup shows that releasing a resource is a
* separate matter: try-with-resources calls close() at a known point.
*/
public final class Reachability {
private Reachability() {
}
/** Returns [reachable, garbage], each in object order. references holds {from, to} pairs. */
public static List<List<String>> collect(List<String> objects, List<String[]> references, List<String> roots) {
Map<String, List<String>> refs = new HashMap<>();
for (String[] r : references) {
refs.computeIfAbsent(r[0], key -> new ArrayList<>()).add(r[1]);
}
Set<String> marked = new HashSet<>();
Deque<String> work = new ArrayDeque<>();
for (String root : roots) {
if (marked.add(root)) work.push(root);
}
while (!work.isEmpty()) {
String current = work.pop();
for (String target : refs.getOrDefault(current, List.of())) {
if (marked.add(target)) work.push(target); // already marked: skip (this is what ends cycles)
}
}
List<String> reachable = new ArrayList<>();
List<String> garbage = new ArrayList<>();
for (String obj : objects) {
if (marked.contains(obj)) {
reachable.add(obj);
} else {
garbage.add(obj); // a tracing GC reclaims it, cycles included
}
}
return List.of(reachable, garbage);
}
/** A resource that records when it is used and closed. */
public static final class TrackedResource implements AutoCloseable {
private final String name;
private final List<String> log;
public TrackedResource(String name, List<String> log) {
this.name = name;
this.log = log;
}
public void use() {
log.add("use " + name);
}
@Override
public void close() {
log.add("close " + name);
}
}
public static List<String> deterministicCleanup() {
List<String> log = new ArrayList<>();
try (TrackedResource file = new TrackedResource("file", log)) {
file.use();
} // close() runs here, whatever the GC does
log.add("after try");
check(log.equals(List.of("use file", "close file", "after try")), "close() runs at the end of try-with-resources");
return log;
}
private static void check(boolean condition, String claim) {
if (!condition) {
throw new AssertionError("Claim failed: " + claim);
}
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/Reachability.java
#pragma once
#include <cassert>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace bekadan::dsa::memory {
// C++ has no tracing garbage collector. collect shows the reachability rule that
// tracing collectors in other languages apply; in C++ lifetime comes from owners
// (scopes, unique_ptr, shared_ptr), and destruction happens at a known point.
struct Collected {
std::vector<std::string> reachable;
std::vector<std::string> garbage;
};
inline Collected collect(const std::vector<std::string>& objects, const std::vector<std::pair<std::string, std::string>>& references,
const std::vector<std::string>& roots) {
std::unordered_map<std::string, std::vector<std::string>> refs;
for (const auto& [from, to] : references) refs[from].push_back(to);
std::unordered_set<std::string> marked;
std::vector<std::string> work;
for (const auto& root : roots) {
if (marked.insert(root).second) work.push_back(root);
}
while (!work.empty()) {
const std::string current = work.back();
work.pop_back();
const auto it = refs.find(current);
if (it == refs.end()) continue;
for (const auto& target : it->second) {
if (marked.insert(target).second) work.push_back(target); // already marked: skip (this is what ends cycles)
}
}
Collected result;
for (const auto& obj : objects) {
if (marked.contains(obj)) {
result.reachable.push_back(obj);
} else {
result.garbage.push_back(obj);
}
}
return result;
}
// RAII: the destructor releases the resource when the owner goes out of scope.
class TrackedResource {
public:
TrackedResource(std::string name, std::vector<std::string>& log) : name_(std::move(name)), log_(log) {}
TrackedResource(const TrackedResource&) = delete;
TrackedResource& operator=(const TrackedResource&) = delete;
~TrackedResource() { log_.push_back("destroy " + name_); }
void use() { log_.push_back("use " + name_); }
private:
std::string name_;
std::vector<std::string>& log_;
};
inline std::vector<std::string> deterministic_cleanup() {
std::vector<std::string> log;
{
TrackedResource file("file", log);
file.use();
} // the destructor runs here: cleanup and freeing happen together
log.push_back("after scope");
assert((log == std::vector<std::string>{"use file", "destroy file", "after scope"}));
return log;
}
// Two shared_ptrs pointing at each other would keep each other alive forever (a leak).
// Making the back link a weak_ptr breaks the cycle.
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> back;
};
inline bool weak_back_link_lets_the_pair_go() {
std::weak_ptr<Node> probe;
{
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;
b->back = a;
probe = a;
assert(!probe.expired());
}
return probe.expired();
}
} // namespace bekadan::dsa::memory
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/reachability.hpp