Garbage Collection
TL;DR
- Garbage Collection (GC) is the process by which the JVM automatically identifies and deletes unused objects from the Heap to free up memory.
- In languages like C++, developers must manually allocate and deallocate memory (
mallocandfree). In Java, this is handled automatically. - It prevents memory leaks but introduces unpredictable pauses in application execution.
Concept
When you write new User(), memory is consumed on the Heap. If your server runs for weeks, processing millions of users, the Heap will eventually become 100% full, crashing the application with an OutOfMemoryError.
To prevent this, the Garbage Collector runs periodically in the background. Its primary job is to determine which objects are “Alive” and which are “Dead”.
- Alive Object: An object that is still being referenced by an active part of the application (e.g., a local variable on a thread’s stack points to it).
- Dead Object (Garbage): An object that has absolutely no references pointing to it anymore. The application has mathematically no way of accessing it ever again. The GC safely deletes these objects.
Examples
public class GarbageCollectionBasics {
public static void main(String[] args) {
// 1. We create an object on the Heap. 'u1' points to it.
User u1 = new User("Alice");
// 2. We create a second object. 'u2' points to it.
User u2 = new User("Bob");
// 3. We reassign u1 to point to the Bob object.
u1 = u2;
// 4. What happened to the "Alice" object?
// Absolutely nothing points to "Alice" anymore. It is completely unreachable.
// It is now officially "Garbage".
// The next time the Garbage Collector runs, "Alice" will be deleted.
}
}
Interview Questions
Q: Can you force the Garbage Collector to run?
A: No. You can “suggest” or “request” that the JVM run the Garbage Collector by calling System.gc() or Runtime.getRuntime().gc(). However, the JVM’s internal heuristics have the final say. It is free to completely ignore your request if it feels a GC cycle is not currently necessary. It is a terrible practice to call System.gc() in production code.
Q: Does Garbage Collection guarantee that memory leaks will never happen?
A: No. Garbage Collection only cleans up unreachable objects. A memory leak in Java occurs when a developer accidentally maintains a reference to an object that they no longer need. For example, if you add objects to a static HashMap (which lives forever) and forget to remove them, the GC sees that the Map is still holding references to them, so it will never delete them. Eventually, the Heap will fill up and crash.