← Back to Chapters

Garbage Collection

♻️ Advance Java — Garbage Collection

? Quick Overview

Garbage Collection (GC) in Java is an automatic memory management process. The JVM continuously identifies unused objects and reclaims memory to prevent leaks and improve performance. In Advanced Java, understanding GC behavior is critical for building scalable and high-performance applications.

? Key Concepts

  • Automatic memory management by JVM
  • Objects become eligible for GC, not explicitly deleted
  • Heap memory divided into generations
  • GC runs in background using different algorithms

? Syntax & Theory

Java uses a generational heap model:

  • Young Generation — New objects (Eden, Survivor spaces)
  • Old Generation — Long-living objects
  • Metaspace — Class metadata (Java 8+)

An object becomes eligible for garbage collection when no active references point to it. The System.gc() call is only a request, not a guarantee.

? Interactive GC Simulator

Visualizing the JVM Heap Memory. Create objects, cut their references, and run the Collector.

Heap Memory Space
Status: Heap Empty

? Code Example — Object Eligibility

? View Code Example
// Demonstrates object eligibility for garbage collection
class DemoGC {
public static void main(String[] args) {
DemoGC obj1 = new DemoGC();
DemoGC obj2 = new DemoGC();

obj1 = null;
obj2 = null;

System.gc();
}
}

? Live Output / Explanation

What Happens Internally?

After setting references to null, both objects become eligible for garbage collection. The JVM may reclaim their memory when it decides to run GC. No direct output is shown because GC execution is JVM-controlled.

? Code Example — finalize() Method

? View Code Example
// Shows finalize method being called before object destruction
class TestGC {
protected void finalize() {
System.out.println("Object collected by GC");
}

public static void main(String[] args) {
TestGC t = new TestGC();
t = null;
System.gc();
}
}

✅ Tips & Best Practices

  • Avoid calling System.gc() frequently
  • Prefer object reuse using pools when possible
  • Minimize object creation in loops
  • Monitor GC using JVM tools like VisualVM

? Try It Yourself

  • Create multiple objects inside a loop and nullify them
  • Run the program with -Xmx and -Xms options
  • Observe GC logs using -verbose:gc