Phase 9 of 25 · Topic 9.2

Generational Cyclic Garbage Collector (Gen 0, Gen 1, Gen 2)

1Concept

To collect circular references that reference counting misses, CPython runs a Generational Cyclic Garbage Collector. It divides container objects into 3 generations: Gen 0 (youngest, scanned frequently), Gen 1 (intermediate), and Gen 2 (oldest, long-lived).

2Architecture Diagram

Gen 0 (New Objects) ---> Survived collections promoted to ---> Gen 1 ---> Promoted to ---> Gen 2

3Code Example

Python 3.12
import gc

print(f"GC Enabled: {gc.isenabled()}")
print(f"GC Generation Thresholds (Gen0, Gen1, Gen2): {gc.get_threshold()}")

# Create circular reference
class CircularNode:
    def __init__(self, name):
        self.name = name
        self.link = None

node_a = CircularNode("A")
node_b = CircularNode("B")
node_a.link = node_b
node_b.link = node_a

del node_a
del node_b

unreachable = gc.collect() # Trigger explicit circular collection
print(f"Unreachable cyclic objects collected by GC: {unreachable}")

4Expected Output

GC Enabled: True
GC Generation Thresholds (Gen0, Gen1, Gen2): (700, 10, 10)
Unreachable cyclic objects collected by GC: 4

5Key Takeaways

  • Default thresholds `(700, 10, 10)` mean Gen 0 runs after 700 net allocations.
  • Only container objects (lists, dicts, custom classes) are tracked by GC; atomic types (int, str) are ignored.
  • Tune thresholds with `gc.set_threshold()` to reduce pause times in high-throughput microservices.