JVM Heap Allocation, Object Liveness, and Garbage Collection

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Prompt

Deliver a self-contained, clearly structured spoken walkthrough of how the Java Virtual Machine manages runtime memory automatically.

Treat this as an asynchronous, one-way technical presentation with no live interviewer present to ask clarifying follow-ups. State your baseline assumptions up front — such as which JDK release and JVM implementation you are anchoring on before contrasting collector options, and how you balance core theory against production troubleshooting — then trace an object's lifecycle end to end:

  1. Where primitives, references, object instances, and native metadata reside at runtime, and how fast concurrent allocation works.
  2. How the runtime determines whether an object is still needed or safe to reclaim (including isolated reference cycles).
  3. Which algorithms reclaim dead memory, why heap generations avoid scanning long-lived state on every pass, and how major JVM collectors balance throughput, pause latency, and RAM footprint.
  4. How these runtime guarantees and limits shape day-to-day Java engineering, including memory leaks and resource management bugs that still occur without manual free calls.

Scope & Expectations

  • Open with explicit JVM/JDK and depth assumptions, using a clear signposted roadmap suited to an unprompted spoken response.
  • Explain stack-versus-heap layout, lock-free thread-local allocation, root-based liveness (contrasted with cyclic references), and generational copying/compaction mechanics.
  • Compare production JVM collectors (Serial, Parallel, G1, ZGC, Shenandoah) across throughput, pause-time targets, and memory overhead.
  • Identify practical Java failure modes — logical retention leaks, excessive allocation churn, unclosed OS handles, and off-heap memory limits — alongside how to prevent and diagnose them.

Step-by-step walkthrough

  1. Structure a self-contained spoken answer up front

    In an asynchronous one-way technical presentation nobody is across the table to steer you, so an explicit roadmap carries half the weight. Organize your talk around the lifecycle of an object from new to reclamation, ending with how that model shapes production Java code:

    1. Allocation     -> Thread stacks vs shared heap, fast pointer-bump TLABs, and off-heap memory
    2. Reachability   -> What "garbage" means: no reference chain from any GC root (handles cycles!)
    3. Reclamation    -> Mark-sweep, mark-compact, copying; stop-the-world pauses vs concurrent barriers
    4. Generations    -> Most objects die young -> cheap copying minor GCs + card tables
    5. Collectors     -> Serial, Parallel, G1, ZGC, Shenandoah (throughput vs pause latency vs RAM)
    6. Code impact    -> Logical memory leaks, allocation rate, and try-with-resources
    

    State your runtime scope in your opening two sentences so your baseline assumptions are explicit: - JVM and JDK version: state that you are describing OpenJDK HotSpot (the standard JVM) on a modern LTS release such as JDK 21, where G1 is the default collector on server-class machines (>= 2 CPUs and >= 2 GB RAM — note that tiny 1-vCPU or 1-GB containers silently get Serial GC unless configured!), and then compare collector options. - Depth: give a clear conceptual model backed by concrete production diagnostics and coding practices, aiming for 3 to 4 minutes (~30–40 seconds per stage).

  2. Where data lives: thread stacks, the shared heap, and TLABs

    Java splits runtime memory between per-thread stacks and one shared heap (plus native off-heap regions):

    Thread 1 Stack                         Shared Java Heap
    +----------------------+               +---------------------------------------------------+
    | frame: checkout()    |               | Young Gen (Eden)                                  |
    |   int qty = 3        |               |  [ Thread 1 TLAB: [Order][Item]|free--->       ]  |
    |   Order o  ------------------>       |  [ Thread 2 TLAB: [Cart]|free---------->       ]  |
    +----------------------+               +---------------------------------------------------+
    
    • Stack frames vs heap objects: Each thread has a private stack of frames (one per active method call) storing local primitives (int, double) and references (compact pointers/addresses). Every actual object instance (new Order()) and every array (new int[1000]) lives on the shared heap — including primitive fields inside an object.
    • Why new is fast (TLAB pointer bumping): If 64 threads locked a shared free list on every new, allocation would crawl. Instead, HotSpot hands each thread a private slice of Eden called a TLAB (Thread-Local Allocation Buffer). Allocating a small object just checks top + size <= end and advances top (bump-the-pointer), taking ~10 CPU instructions with zero locks! This works because young collections evacuate survivors and leave free space as one contiguous slab.
    • Object memory overhead: Objects carry header metadata. On 64-bit HotSpot (JDK 21 default compressed pointers), every object has a 12-byte header (8-byte mark word + 4-byte class pointer) padded to an 8-byte boundary:
    new Object()     -> 12B header + 4B alignment padding              =   16 bytes
    new Integer(42)  -> 12B header + 4B int value                      =   16 bytes (4x a raw 4B int!)
    new int[1000]    -> 12B header + 4B array length + 1000 * 4B ints  = 4016 bytes
    
    • Escape analysis & off-heap memory: If HotSpot's JIT (Just-In-Time) compiler (which compiles hot bytecode into native machine code at runtime) proves via escape analysis that a temporary object never leaves a method, it can break the object into CPU registers (scalar replacement) so no heap allocation happens at all. Conversely, class metadata (Metaspace), thread stacks (-Xss), JIT machine code, and NIO direct ByteBuffers live in native off-heap memory — so -Xmx caps only the Java heap, not the container's total RAM usage!
  3. What makes an object garbage: reachability from GC roots

    Java does not use reference counting. Instead, the garbage collector defines liveness by reachability: an object is live if and only if it can be reached by following a chain of references starting from at least one GC root. Every object with no path from any root is unreachable (garbage) and eligible for reclamation.

    The main GC roots — pointers the running program can touch directly without dereferencing another heap object — are: 1. Local variables and operand-stack values in active stack frames of all live threads. 2. static fields of loaded classes. 3. Active JNI (Java Native Interface) references held by C/C++ native code. 4. Objects currently locked as synchronized monitors and internal JVM system references.

    Check how reachability effortlessly handles isolated reference cycles:

    While local vars point in:               After setting a = null; b = null:
      [Stack root a] ---> ( Node A )           [Stack root a = null]     ( Node A )
                            |    ^                                         |    ^
                            v    |                                         v    |
      [Stack root b] ---> ( Node B )           [Stack root b = null]     ( Node B )
      Both reachable -> KEPT                   Zero paths from any root -> BOTH RECLAIMED!
    

    Even though A.next points to B and B.next points to A (so each object still has incoming reference count 1), neither can be reached from any GC root once a and b become null or their method returns. A tracing collector starts at the roots, never visits A or B, and reclaims both cleanly.

    class Node {
        Node next;
    }
    
    void buildDetachedCycle() {
        Node a = new Node();
        Node b = new Node();
        a.next = b;
        b.next = a;
        // When this method returns, stack roots a and b disappear;
        // the A <-> B cycle has no path from any GC root and is reclaimed.
    }
    
  4. How memory is reclaimed: mark-sweep, mark-compact, copying, and barriers

    Every production JVM collector combines three classical reclamation mechanisms after tracing from GC roots:

    Algorithm      How it reclaims dead space                         Work proportional to    Main trade-off
    -------------  -------------------------------------------------  ----------------------  ---------------------------------------
    Mark-Sweep     Mark live objects; record dead gaps in free lists  Live graph + heap scan  Heap fragmentation (Swiss-cheese holes;
                                                                                              ruins fast pointer-bump allocation)
    Mark-Compact   Mark live objects, slide them together at one end  Live graph + live move  Longer pause / extra pass to rewrite
                   of the region, and update moved addresses                                  every reference to moved objects
    Copying        Copy live survivors into an empty reserve region;  ONLY live survivors!    Requires empty reserve space (headroom)
    (Evacuation)   wipe the entire old region free in one step                                to copy survivors into
    

    Notice why copying is magical when survival rates are low: if a 512 MB region holds 15 MB of live objects and 497 MB of dead temporary objects, copying touches only the 15 MB of survivors and resets the 512 MB pointer in O(1) without ever inspecting the 497 MB of dead objects!

    Collectors also differ in whether application threads run during collection: - Stop-the-World (STW): All application threads pause at a safepoint (a clean instruction boundary where every thread's stack references are known), the collector runs undisturbed, and threads resume. Simple and high-throughput, but pauses grow with heap/live-set size. - Concurrent collection + barriers: Collector threads mark (and in modern collectors, relocate) objects while application threads keep mutating references! To prevent race conditions, the JIT compiler injects tiny instructions called barriers around pointer reads or writes: - Write barriers (used by G1): intercept obj.field = ref writes so concurrent Snapshot-At-The-Beginning (SATB) marking never misses an object that was live when marking started. - Load barriers + colored pointers (used by ZGC / Shenandoah): intercept ref = obj.field reads and transparently heal stale addresses on the fly if a concurrent collector thread just relocated that object!

  5. Generational collection: exploit the fact that most objects die young

    In almost every Java service, 90%–98% of allocated objects die within milliseconds (HTTP request wrappers, StringBuilder buffers, stream iterators, JSON parse nodes) — an empirical rule called the weak generational hypothesis. Scanning multi-gigabyte long-lived caches on every GC just to clean up temporary request garbage would waste huge CPU time, so HotSpot divides the heap into Generations:

    Young Generation (collected often by copying)            Old / Tenured Generation (collected rarely)
    +-----------------------+-------------+-------------+    +-----------------------------------------+
    |         Eden          | Survivor S0 | Survivor S1 | -> | Long-lived caches, singletons, sessions |
    +-----------------------+-------------+-------------+    +-----------------------------------------+
                                                                   |  (Old-to-Young pointer)
                                                             Card Table: [clean][DIRTY][clean][clean]
                                                                         (each byte covers 512B of Old Gen)
    

    Walk through a concrete numeric trace (512 MB Eden, 100 MB/s allocation rate, 3% survival): 1. Minor GC every ~5.1 seconds: New objects fill Eden via TLABs in 512 / 100 ≈ 5.1 s. A fast minor GC traces Young Gen, copies the ~ 15 MB of live survivors from Eden + active Survivor S0 into empty S1, and leaves Eden + S0 completely empty. 2. Aging and promotion (tenuring): Each survived minor GC increments a 4-bit age counter in the object's header (maximum tenuring threshold = 15 in HotSpot). Objects reaching the threshold (or overflowing the survivor space, which dynamically lowers the threshold) are promoted into the Old Generation, which is collected far less often via concurrent marking + mixed/major evacuations. 3. Remembered sets / Card Table: What if an Old-Gen object points to a Young-Gen object (oldCache.latest = youngObj)? Scanning 30 GB of Old Gen during every minor GC would ruin generational speed! Instead, a fast write barrier marks a 1-byte entry dirty in a Card Table (where each byte represents a 512-byte slice of Old Gen), so minor GC scans only dirty 512-byte cards (or per-region remembered sets in G1) as extra roots.

  6. Collector trade-offs: Serial, Parallel, G1, ZGC, and Shenandoah

    Every garbage collector balances three competing goals — Throughput (% of total CPU spent running your code rather than GC/barriers), Latency (worst-case pause duration), and Footprint (extra RAM needed for headroom, remembered sets, and copying):

    Collector    How it works                                          Best fit
    -----------  ----------------------------------------------------  ---------------------------------------------------
    Serial       Single GC thread; STW copying young + compacting old  Tiny heaps (< ~200 MB), 1-CPU containers, CLI tools
    Parallel     Multi-threaded STW young + STW compacting old         Offline batch / spark / ML ETL jobs maximizing raw
                 (default through JDK 8)                               throughput where 500 ms+ pauses do not matter
    G1           Splits heap into 1-32 MB regions; concurrent global   Default since JDK 9; balanced microservices aiming
                 marking + STW evacuation of "Garbage-First" regions   for ~50-200 ms pauses (-XX:MaxGCPauseMillis=200)
    ZGC          Concurrent marking AND concurrent relocation via      Latency-critical services & huge heaps (16 GB-16 TB)
                 load barriers; Generational ZGC added in JDK 21       needing sub-millisecond (< 1 ms) pauses; costs ~5-15%
                 (default ZGC mode from JDK 23)                        barrier CPU + extra heap headroom
    Shenandoah   Concurrent marking + concurrent evacuation via load   Same sub-millisecond low-pause niche as ZGC (shipped
                 reference barriers                                    in most OpenJDK distros, omitted from Oracle JDK)
    

    (Historical note: CMS was deprecated in JDK 9 and removed in JDK 14 because it did not compact and suffered fragmentation; Epsilon in JDK 11 allocates without ever collecting, useful for ultra-short jobs and allocation benchmarks.)

    Practical rule: start with G1, measure your live set (heap occupied right after a full mark cycle) and give the heap 2x–3x that live set, switch to Generational ZGC when tail-latency SLAs forbid tens-of-milliseconds pauses, or switch to Parallel for pure batch throughput.

  7. What this means for everyday Java code (and how leaks still happen)

    Automatic memory management prevents dangling pointers (use-after-free) and double frees, but it does not prevent logical memory leaks — objects your program will never use again that accidentally stay reachable from a GC root: - Unbounded static maps or in-memory caches without TTL or size eviction (e.g., static Map<String, Session> missing remove() on logout or timeout). - Unremoved listeners / callbacks registered on long-lived publishers. - ThreadLocal values on pooled threads (web server worker threads live forever, so forgetting threadLocal.remove() in a finally block leaks per-request payloads). - Inner classes / lambdas unintentionally capturing a reference to a large enclosing object, or mutating a HashMap key after insertion so remove(key) looks in the wrong hash bucket. - ClassLoader leaks during hot-reloads, filling native Metaspace.

    public final class SessionRegistry {
        // Static field = GC root! Every entry kept here stays reachable forever.
        private static final Map<String, Session> ACTIVE = new ConcurrentHashMap<>();
    
        public static void onLogin(Session s) {
            ACTIVE.put(s.id(), s);
        }
    
        public static void onLogoutOrExpire(String id) {
            // Without this removal (or a bounded/expiring cache), sessions leak until OOM!
            ACTIVE.remove(id);
        }
    }
    

    Four more day-to-day engineering rules follow directly from how the JVM works: 1. Allocation rate drives GC frequency: avoid needless churn on hot paths (such as autoboxing Long sum = 0L; sum += i; in a million-iteration loop, which allocates a 16-byte Long object every iteration instead of adding a primitive long). 2. GC only manages memory, not OS handles: sockets, files, and JDBC connections must be closed deterministically with try-with-resources (AutoCloseable), because GC runs when the heap fills, not when Linux hits its file-descriptor limit! 3. Budget container memory beyond -Xmx: leave ~20%–30% container RAM above -Xmx for Metaspace, thread stacks, code cache, and direct buffers (and remember default -XX:MaxRAMPercentage=25.0 leaves 75% of a single-process container's heap unused unless configured). 4. Read the OutOfMemoryError detail message: Java heap space, GC overhead limit exceeded, Metaspace, Direct buffer memory, and unable to create native thread each point to a completely different pool.

  8. Polished 3-minute spoken script

    Here is how to deliver the complete model smoothly in about three minutes on camera:

    "I'll explain Java's automatic memory management as implemented in OpenJDK HotSpot on a modern LTS release like JDK 21, where G1 is the default collector on multi-core servers, and connect the mechanics to how we write and operate Java services.

    First, allocation. Every thread has its own call stack holding primitive locals and object references, while all objects and arrays live on a shared heap. Even though the heap is shared, new is tiny and lock-free: HotSpot gives each thread a private Thread-Local Allocation Buffer, or TLAB, in the young generation, so allocating an object is just bumping a pointer forward. Note that class metadata in Metaspace, thread stacks, and direct ByteBuffers live in native memory outside -Xmx.

    Second, reachability. Java never uses reference counting; an object is live if and only if a chain of references reaches it from a GC root — active thread stack variables, static fields, JNI handles, or active monitors. Tracing from roots naturally reclaims isolated cycles, like two nodes pointing only to each other, because zero paths reach them from any root.

    Third, reclamation and generations. Collectors combine mark-sweep, mark-compact, and copying. Because empirical workloads obey the weak generational hypothesis — over 90% of objects die within milliseconds — HotSpot splits the heap into a Young Generation and an Old Generation. New objects fill Eden; a minor GC copies only the small fraction of live survivors into a Survivor space, ages them, and promotes long-lived survivors to Old Gen. Copying makes minor GCs proportional to live survivors rather than dead garbage, and a write-barrier Card Table tracks old-to-young pointers so minor GCs don't scan the Old Generation.

    Fourth, collector trade-offs. Parallel GC uses stop-the-world threads to maximize batch throughput; G1 divides the heap into regions and evacuates the fullest garbage regions first to hit ~200-millisecond pause targets; and Generational ZGC and Shenandoah use load barriers to relocate objects concurrently, keeping pauses under a millisecond even on multi-hundred-gigabyte heaps at the cost of barrier CPU and memory headroom.

    Finally, what this means for my code: logical memory leaks still happen whenever unused objects stay reachable in unbounded static caches, unremoved listeners, or uncleaned ThreadLocals; high allocation rates increase GC pressure; OS handles still require try-with-resources; and in production I rely on GC logs, JFR, and heap dumps to measure rather than guess."

Intuition & how it works

Think of the Java Virtual Machine (JVM) heap like a busy restaurant with an automated bussing crew. Instead of making chefs wash a plate before serving every dish (manual malloc/free), each chef grabs clean plates instantly off a personal stack at their station (TLAB bump-the-pointer allocation). Periodically, bussers check which tables still have guests seated (GC roots such as active stack variables and static fields) and trace every dish reachable from those tables (reachability). For fast-turnover appetizer tables where 95% of plates are finished within minutes (Young Generation), bussers simply move the 5% of still-active dishes onto a fresh cart and wipe the whole table clean in one sweep (copying collection); only dishes that stay in use across many rounds move to long-term banquet tables (Old Generation), which get deep-cleaned much less often.

Why do common beginner mental models break down in production? First, assuming "Java has garbage collection, so memory leaks are impossible" fails whenever your code leaves dead sessions sitting inside a static Map — to the collector, those objects are still reachable from a seated guest, so they can never be cleared! Second, assuming "creating objects is expensive because GC has to free each one" misses how copying young-generation GC works: dead objects in Eden cost zero work per object to free because only surviving objects are copied. Third, assuming -Xmx caps your Docker container's RAM overlooks native off-heap memory (Metaspace, thread stacks, JIT code, direct buffers), leading to Linux OOMKilled crashes when the heap itself looks half empty.

Walk through a concrete numeric trace on 64-bit HotSpot (512 MB Eden, 100 MB/s allocation rate, 3% survivor rate):

1. Fast allocation:
   `Order o = new Order()` -> 8-byte reference `o` on Thread Stack; Order object bumped in Thread's TLAB in ~10 cycles.

2. Minor copying GC every ~5.1 seconds (512 MB / 100 MB/s):
   97% (~497 MB) of request objects are already unreachable -> untouched!
   3%  (~15 MB) of live objects are copied to Survivor space in a few milliseconds; Eden resets in O(1).

3. Cycle vs Leak contrast:
   - Detached cycle `A <-> B` after `a = null; b = null`: 0 paths from GC roots -> BOTH reclaimed.
   - Forgotten `Session` in `static Map ACTIVE`: 1 path from static GC root -> NEVER reclaimed (memory leak!).

Key points

  • References on thread stacks, objects on the shared heap. Local primitives and references live in per-thread stack frames; objects and arrays live on the heap (12-byte header + 8-byte alignment on default 64-bit HotSpot), allocated lock-free via TLABs (or elided onto registers when JIT escape analysis proves an object never escapes).
  • Liveness is reachability from GC roots, namely active stack locals across threads, static class fields, JNI native handles, and active monitors — not reference counts, so detached reference cycles are collected automatically.
  • Mark-sweep, mark-compact, and copying form the reclamation building blocks, paired with stop-the-world (STW) safepoints or concurrent read/write barriers (G1's SATB write barrier; ZGC/Shenandoah's load barriers for concurrent relocation).
  • Generational GC exploits "most objects die young": frequent minor copying GCs evacuate Eden + Survivor spaces in time proportional to live survivors, promote objects up to age 15 into Old Gen, and use a 512-byte Card Table (or per-region remembered sets) to track old-to-young references cheaply.
  • Collectors trade throughput, latency, and footprint: Serial (1-CPU / tiny containers), Parallel (maximum batch throughput), G1 (default region-based collector targeting ~ 200 ms pauses), and Generational ZGC / Shenandoah (< 1 ms pauses independent of heap size, paying barrier CPU and RAM headroom).
  • Java code still owns logical leaks, allocation rate, off-heap sizing, and OS handles: bound caches, call ThreadLocal.remove(), close I/O via try-with-resources, leave container headroom above -Xmx, and diagnose with GC logs, JFR, and heap dumps.

Common mistakes

  • Claiming Java uses reference counting or struggles to collect circular references A <-> B.
  • Saying "all primitives live on the stack": a primitive local variable lives in a stack frame, whereas a primitive instance field (class Point { int x, y; }) lives inside its enclosing object on the heap!
  • Confusing "unused by business logic" with "unreachable": any forgotten entry in a static collection, listener list, or ThreadLocal remains reachable from a GC root and leaks permanently.
  • Talking about "the Java GC" as a single algorithm without specifying HotSpot and distinguishing stop-the-world Parallel, region-based G1, and concurrent-relocating ZGC/Shenandoah (or overlooking that 1-CPU containers default to Serial!).
  • Calling System.gc() or overriding finalize() to manage memory or close files/sockets instead of using try-with-resources.
  • Setting -Xmx equal to 100% of a container's memory limit, leaving zero room for Metaspace, thread stacks, JIT code cache, and NIO direct buffers and triggering OS OOMKilled terminations.

Follow-up questions

  • A production Java service suffers recurring multi-second latency freezes. How would you confirm whether GC is responsible and remediate the issue? Enable unified GC and safepoint logging (-Xlog:gc*,safepoint:file=gc.log:time,uptime,level,tags) and check whether multi-second STW timestamps line up with your p99 latency spikes. Inspect the pause cause and gc+cpu times: if real wall-clock time (3.2s) vastly exceeds user + sys CPU time (0.1s), the OS is swapping to disk or throttling container CPU rather than doing GC work; if G1 logs Pause Full (Allocation Failure), concurrent marking could not keep up (because of a memory leak where post-GC occupancy climbs monotonically, heap -Xmx sized too close to the live set, or huge >= 50%-region "humongous" array allocations). Capture a heap dump (jcmd <pid> GC.heap_dump /tmp/heap.hprof analyzed in Eclipse MAT) plus a low-overhead JFR (Java Flight Recorder) profile to fix leaks and allocation hotspots, then either give G1 headroom / earlier marking (-XX:InitiatingHeapOccupancyPercent) / larger regions (-XX:G1HeapRegionSize) or switch to Generational ZGC (-XX:+UseZGC -XX:+ZGenerational in JDK 21; -XX:+UseZGC in JDK 23+) for sub-millisecond pauses.
  • How do SoftReference, WeakReference, and PhantomReference differ in Java, and what practical problem does each solve? All three are java.lang.ref wrappers that reference an object without forcing it to stay strongly reachable, optionally notifying a ReferenceQueue when cleared. SoftReference stays alive until memory pressure rises and is guaranteed to be cleared before throwing OutOfMemoryError (historically used for memory-sensitive caches, though bounded LRU/W-TinyLFU caches like Caffeine are much more predictable in production). WeakReference is cleared on the very next GC cycle that sees no strong or soft path to the target — ideal for canonicalizing tables or attaching metadata to externally owned keys (WeakHashMap, keeping in mind that only the keys are weak, so values must not strongly reference their own key!). PhantomReference always returns null from get() and is enqueued after the object becomes unreachable so you can safely free associated off-heap/native resources without any risk of object resurrection (java.lang.ref.Cleaner is built on phantom references).
  • What makes Object.finalize hazardous in real systems, and which modern Java mechanisms supersede it? finalize() runs at an unspecified future time on background finalizer threads (or never at all if the heap stays roomy), so scarce OS handles like sockets and file descriptors run out long before GC runs. Worse, finalizable objects survive at least one extra GC cycle, slow or blocked finalizers stall the finalization queue until the JVM crashes with OutOfMemoryError, swallowed exceptions hide bugs, and buggy code inside finalize() can accidentally "resurrect" a dead object by storing this into a static field (finalize() was deprecated in JDK 9 and deprecated for removal in JDK 18). Replace it with AutoCloseable + try-with-resources for deterministic cleanup at scope exit, backed optionally by java.lang.ref.Cleaner strictly as a fallback safety net when a caller forgets close().
// Deterministic cleanup: close() runs immediately at '}' even if process() throws
try (var stream = java.nio.file.Files.newInputStream(path)) {
    process(stream);
}
  • What are the runtime trade-offs between tracing garbage collection and reference-counted memory management? Reference counting (used in CPython, Swift, and Rust's Rc/Arc) increments and decrements an integer count on every pointer copy/drop and frees the object the exact instant its count hits 0, giving deterministic destruction and low memory overhead — but it pays constant per-assignment CPU overhead (especially expensive atomic instructions across threads), suffers latency spikes when freeing deep object trees cascades, and leaks reference cycles (A <-> B) unless paired with manual weak pointers (Swift/Rust) or a backup cycle-tracing collector (CPython). Tracing GC (Java, Go, C#) pays zero cost when copying local references, collects arbitrary cycles automatically, and compacts survivors so allocation is a fast pointer bump, trading delayed reclamation, extra RAM headroom (2x–3x live set), and collector CPU/barriers for higher peak throughput and memory safety without manual weak-cycle annotations.

Follow-up questions

Similar questions

More State interview questions

All 1 State questions →