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.
Java uses a generational heap model:
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.
Visualizing the JVM Heap Memory. Create objects, cut their references, and run the Collector.
// 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();
}
}
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.
// 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();
}
}
System.gc() frequently-Xmx and -Xms options-verbose:gc