Garbage Collection
TL;DR
- Garbage Collection (GC) is an automated process in the JVM that reclaims Heap memory by deleting objects that are no longer reachable by the application.
- It prevents memory leaks and manual memory management (like
malloc/freein C++). - The Heap is divided into Generations: Young (for short-lived objects) and Old/Tenured (for long-lived objects).
Concept
In C++, you must explicitly allocate and free memory. If you forget to free it, your server crashes from a memory leak.
In Java, you just create objects using new. A background daemon thread (the Garbage Collector) periodically scans the Heap. It looks for “GC Roots” (active threads, static variables). It traces every pointer from the roots to every object. Any object that cannot be reached (e.g., a local variable that was lost when a method ended) is considered “dead.” The GC deletes it and compacts the remaining memory.
Because 95% of objects die almost instantly (e.g., intermediate strings), the Heap is split. New objects go to the Young Generation. When it fills up, a “Minor GC” occurs, instantly wiping out the dead objects. Objects that survive multiple Minor GCs are promoted to the Old Generation.
Examples
public class GCDemo {
public static void main(String[] args) {
// Object A is created on the heap. 'user1' points to it.
User user1 = new User("Alice");
// Object B is created on the heap. 'user2' points to it.
User user2 = new User("Bob");
// We reassign the pointer. 'user1' now points to Object B.
user1 = user2;
// At this exact moment, Object A ("Alice") has ZERO pointers pointing to it.
// It is "unreachable".
// The next time the Garbage Collector runs, Object A will be destroyed and
// its memory reclaimed.
// We can politely ask the JVM to run the GC, but it is just a suggestion.
// The JVM decides when it is optimal to run it.
System.gc();
}
}
Interview Questions
Q: What is a “Stop-The-World” pause?
A: When the Garbage Collector runs (specifically a Major GC on the Old Generation), it must guarantee that the application doesn’t create or move objects while it is actively deleting memory. To do this, the JVM forcibly pauses every single application thread. The application is completely frozen. If the heap is massive (e.g., 64GB) and the GC algorithm is inefficient, this pause can last for several seconds, causing massive latency spikes in production systems.
Q: What is the G1 Garbage Collector?
A: G1 (Garbage-First) GC is the default Garbage Collector for modern Java (Java 9+). Older collectors (like Parallel GC) would freeze the entire application to clean the massive Old Generation. G1 splits the entire heap into thousands of small, independent regions. Instead of cleaning the whole heap at once, it calculates which regions contain the most garbage (“Garbage First”) and cleans them concurrently in tiny increments, ensuring that “Stop-The-World” pauses rarely exceed a target latency (e.g., 200 milliseconds).