Back to the 2020 paper

Module III: Basics of Web Programming

20207m

Explain Java garbage collection mechanism.

Worked SolutionAI Assisted

Answer: Java Garbage Collection Mechanism

1. What is Java Garbage Collection (GC)?

Garbage Collection (GC) in Java is an automated memory management process managed by the Java Virtual Machine (JVM) that tracks objects allocated on the heap and reclaims memory occupied by objects that are no longer reachable or referenced by any active part of the running program.

Unlike languages like C/C++ where developers must manually allocate and free memory (malloc()/free(), new/delete), Java automatically prevents memory leaks and dangling pointer errors.

+---------------------------------------------------------------------------------+
|                                    JVM HEAP                                     |
|                                                                                 |
|  +----------------------------- Young Gen ----------------------------+         |
|  |  +----------------+  +--------------------+  +--------------------+  |  Old  |
|  |  |      Eden      |  | Survivor 0 (From)  |  |  Survivor 1 (To)   |  |  Gen  |
|  |  |  (New Objects) |  |   (Minor GC S0)    |  |   (Minor GC S1)    |  | (Tenured)
|  |  +----------------+  +--------------------+  +--------------------+  |       |
|  +--------------------------------------------------------------------+---------+

2. When Does an Object Become Eligible for GC?

An object on the heap is eligible for garbage collection when it has no live references pointing to it from the GC Roots (stack frames, static variables, JNI references).

Common Scenarios:

  1. Nullifying a Reference Variable:
    Student s = new Student("Alice");
    s = null; // Original Student object is now eligible for GC
    
  2. Reassigning a Reference Variable:
    Student s1 = new Student("Alice");
    Student s2 = new Student("Bob");
    s1 = s2; // Original "Alice" object is now orphaned and eligible for GC
    
  3. Objects Created Inside a Method Scope:
    • Once the method finishes execution, local reference variables popped from the call stack leave created objects unreferenced.
  4. Island of Isolation:
    • Two objects reference each other, but neither is referenced by any active live reference from root threads.

3. Generational Garbage Collection Hypothesis

Most objects in software have short lifespans (created, used, and discarded quickly). JVM divides the Heap into Generations:

A. Young Generation

  • Eden Space: All new objects are initially created here.
  • Survivor Spaces (S0 & S1): Objects that survive a Minor GC in Eden are moved between S0 and S1, incrementing their age counter.

B. Old (Tenured) Generation

  • Objects that survive multiple Minor GC cycles (threshold age, typically 15) are promoted to the Old Generation.
  • Cleaned up during a Major GC (Full GC).

C. Metaspace (Non-Heap)

  • Stores class metadata and static variables (replaces PermGen in Java 8+).

4. How Garbage Collection Works: The Mark-and-Sweep Process

  1. Mark Phase: The GC identifies and marks all live, reachable objects by traversing reference trees starting from GC Roots.
  2. Sweep Phase: The GC sweeps the heap and frees the memory occupied by all unmarked (unreachable) objects.
  3. Compact Phase (Optional): Moves all surviving objects together to eliminate memory fragmentation and create contiguous free space.

5. Explicit GC Request and Finalization

  • Requesting GC: Developers can suggest garbage collection using:
    System.gc(); // or Runtime.getRuntime().gc();
    
    (Note: This only requests GC; the JVM decides when to actually execute it).
  • finalize() Method: Historically invoked by the JVM before reclaiming an object's memory (deprecated in modern Java in favor of AutoCloseable / Cleaner).

6. Popular JVM Garbage Collectors

Garbage Collector Use Case Key Characteristics
Serial GC Small, single-threaded apps Single-threaded, basic Mark-Sweep-Compact
Parallel GC High-throughput batch jobs Multi-threaded Minor and Major GC
G1 GC (Garbage-First) Large heap sizes (>4GB), default in modern Java Divides heap into equal regions; prioritizes regions with most garbage
ZGC / Shenandoah Ultra-low latency enterprise apps Sub-millisecond pause times concurrent GC

Similar questions