How garbage collection works in Java
Let me explain how garbage collection works in Java.
Garbage collection in Java is an automated memory management process that identifies and removes objects that are no longer being used. Here's how it works:
Identification of Garbage
1.Java uses a concept called "reachability" to identify garbage
2. Objects still referenced from:
Active threads
Static fields
Local variables in active methods are considered "reachable" and kept alive
3. Objects that can't be reached are marked as garbage
Generational Collection
Java divides the heap into different generations:
Young Generation (Eden Space + Survivor Spaces)
Old Generation (Tenured)
Metaspace (for class metadata)
Garbage Collection Process
Minor GC (Young Generation)
Most objects die young
Quick and efficient
survivors move to Survivor spaces
After surviving multiple cycles, objects promote to Old Generation
Major GC (Old Generation)
Less frequent but more thorough
Usually causes "Stop the World" events
More time-consuming
Common GC Algorithms
Serial GC (single thread)
Parallel GC (multiple threads)
MS (Concurrent Mark Sweep)
G1 GC (Garbage First)
ZGC (Z Garbage Collector)
Example of an object becoming eligible for garbage collection:
javaCopypublic void example() {
Student student = new Student(); // Object created
student = null; // Object becomes eligible for GC
// Or when method ends, local reference goes out of scope
}
Hello
4 个月Love this
APM tools || Infra Monitoring Tools Specialist || MFAPM || Appdynamics Admin
4 个月Useful tips
Performance Test Engineer @ EY | Ex-Capgemini| Load Runner | LRE | Dynatrace | Load Runner Cloud| Performance Center | Splunk | PERFECTO | True client web
4 个月Intersting ! Thank you for your post . Hopefully we will see more informative posts like this in future
Providing: AIOps& Observability Consulting and Corporate Training services
4 个月Insightful