Garbage Collection Basics
TL;DR
- Garbage Collection (GC) is a daemon thread running in the background of the JVM.
- It automatically reclaims memory by deleting objects that are no longer reachable by the application.
- It ensures developers don’t have to manually deallocate memory, vastly reducing memory leaks and segmentation faults.
Concept
In C++, developers manually use malloc() and free(). If they forget to call free(), the application leaks memory. If they call free() but try to access the memory later, it causes a catastrophic crash (Dangling Pointer).
Java designers decided that manual memory management was too error-prone. The JVM provides a Garbage Collector.
The GC operates on a simple principle: Reachability.
Starting from known “Alive” roots (like local variables on a thread’s stack or static variables), it traces every reference it can find. Any object that cannot be reached through this tracing process is deemed “unreachable” (Garbage) and its memory is safely wiped.
Examples
public class GcBasics {
public static void main(String[] args) {
// 1. We allocate memory on the heap. 'str' is a reference on the stack.
String str = new String("Hello GC");
// 'str' is currently reachable. The GC will not touch it.
System.out.println(str);
// 2. We sever the connection.
str = null;
// The String object "Hello GC" still exists on the heap right now,
// but it is mathematically unreachable by our code.
// It is now eligible for Garbage Collection.
// 3. The JVM will eventually run the GC in the background to delete it.
// We can nicely ask the JVM to do it now, but there's no guarantee it will!
System.gc();
}
}
Interview Questions
Q: What makes an object “eligible” for Garbage Collection?
A: An object becomes eligible for GC when it is completely unreachable by any active thread in the application. This happens when:
- All references to it are explicitly set to
null. - The reference variable goes out of scope (e.g., a method finishes and its local variables are destroyed).
- The object is part of an “Island of Isolation” (e.g., Object A points to Object B, and Object B points to Object A, but nothing in the main application points to either A or B).
Q: Is Garbage Collection deterministic?
A: No, it is non-deterministic. As a Java developer, you have absolutely zero control over when the Garbage Collector runs, how long it will take, or which specific objects it will decide to clean up during a cycle. The JVM executes it based on internal heuristics and memory pressure.