Garbage collection in Java
- by utk
What is Garbage Collection?
Garbage Collection in Java is the process of automatically freeing memory by deleting
objects that are no longer reachable by any part of the program.
Java handles memory management so you don't have to explicitly free() or delete()
objects (unlike C/C++).
🔹 Why Do We Need It?
• Prevent memory leaks.
• Avoid OutOfMemoryError.
• Ensure efficient use of heap memory.
• Simplify development — less worry about manual memory management.
🔹 Key Concepts
1. Heap Memory
Where all objects in Java are stored. Divided into:
• Young Generation (Young Gen)
o Where new objects are created.
o Includes:
▪ Eden Space – where objects are first created.
▪ Survivor Spaces – S0 and S1, for objects that survive garbage
collection.
• Old Generation (Tenured Gen)
o Holds long-lived objects that survived several GCs.
• Metaspace (Java 8+)
o Stores class metadata (like class definitions).
2. Reachability
An object is eligible for GC when it's no longer referenced.
java
CopyEdit
String s = new String("Hello");
s = null; // Now "Hello" is eligible for GC
🔹 How Garbage Collection Works
1. Mark – Identify which objects are still reachable.
2. Sweep – Delete unreferenced (unreachable) objects.
3. Compact – Rearrange memory to reduce fragmentation.
🔹 Types of Garbage Collectors
Collector Name Description
Serial GC Single-threaded, good for small apps
Uses multiple threads for GC (default in many
Parallel GC
cases)
CMS (Concurrent Mark Sweep) Low pause time, deprecated in Java 14
Low pause, handles large heaps, default from Java
G1 (Garbage First)
9+
ZGC (Java 11+) Scalable, low latency, for very large heaps
Shenandoah GC Low-pause collector from RedHat (Java 12+)
🔹 Forcing Garbage Collection (Not Recommended)
java
CopyEdit
System.gc(); // Just a request, not guaranteed
Use only in specific test or tuning cases. The JVM decides the best time to collect.
🔹 Example of GC in Action
java
CopyEdit
public class GCDemo {
public static void main(String[] args) {
GCDemo obj = new GCDemo();
obj = null; // Now eligible for GC
// Requesting GC
System.gc();
}
@Override
protected void finalize() throws Throwable {
System.out.println("Garbage Collected!");
}
}
🔹 Best Practices
Let the JVM handle GC
Avoid memory leaks by cleaning up references
Use tools like VisualVM, jconsole, or YourKit for monitoring
Profile large applications for GC performance