Java Garbage Collection
Every object you create takes space in memory. Garbage collection is the Java feature that finds objects your program no longer uses and frees their space. You write no cleanup code. The JVM handles the job in the background.
A Hotel Housekeeping Example
A hotel has many rooms. Guests check out and leave rooms empty. Housekeeping staff visit rooms that nobody uses and clean them for new guests. Garbage collection works like that staff. Objects that nobody refers to are the empty rooms.
Where Objects Live
Java stores objects in an area called the heap. Variables live on the stack and hold addresses that point to heap objects.
Stack Heap
+-----------+ +---------------+
| s1 -------+---------> | "Hello" |
+-----------+ +---------------+
| s2 -------+---------> | "World" |
+-----------+ +---------------+
| "Old data" | no arrow points here
+---------------+ --> eligible for cleanup
When Does an Object Become Garbage
An object becomes garbage when no live variable can reach it. Three common cases create garbage.
1. Reassigning a Reference
String name = new String("Asha");
name = new String("Ravi"); // "Asha" object loses its pointer
2. Setting a Reference to Null
Student s = new Student();
s = null; // the Student object loses its pointer
3. Leaving a Scope
void run() {
Student temp = new Student();
} // temp disappears when the method ends
Diagram: Before and After a Collection
Before After
[A used][B unused][C used] [A used][ ][C used]
[D unused] free space
The Generations Idea
Most objects live a short time. Java splits the heap into regions to take advantage of that fact.
| Region | Holds | Cleanup Frequency |
|---|---|---|
| Young generation | Brand-new objects | Often and fast |
| Old generation | Objects that survived many cleanups | Rarely and slower |
new object --> Young generation --survives several rounds--> Old generation
|
+-- unused objects removed quickly
The System.gc() Request
The call System.gc() asks the JVM to run a cleanup. The JVM treats it as a polite request and decides on its own. Real programs almost never need this call.
System.gc(); // a request, not a command
Garbage Collectors in Modern Java
The JVM offers several collectors. Each collector balances speed and pause time in a different way. The G1 collector serves as the default in recent Java versions. Beginners can ignore the settings and rely on the defaults.
Memory Leaks in Java
Java still leaks memory when a program keeps a pointer to an object that it never uses again. The collector sees the pointer and keeps the object alive.
static ArrayList<byte[]> cache = new ArrayList<>();
void load() {
cache.add(new byte[1000000]); // never removed
}
Each call adds one million bytes that never leave. Remove old entries from long-lived lists and maps.
Good Habits
- Create objects only when you need them
- Remove items from static lists and maps after use
- Close files and connections with try-with-resources
- Avoid creating thousands of temporary objects inside loops
Common Mistakes
- Calling System.gc() and expecting instant cleanup
- Believing that Java programs never run out of memory
- Relying on the finalize method, which Java has deprecated
Quick Summary
- The JVM frees objects that nobody can reach
- Young objects die fast and old objects stay long
- Static collections cause most leaks
