What is Garbage Collection in Java?
Garbage Collection (GC) in Java is the automatic process of identifying and removing unused objects from memory.
In simple words:
Garbage Collector automatically frees heap memory by deleting objects that are no longer needed.
Why Garbage Collection is Important?
Garbage Collection helps:
- Prevent memory leaks
- Automatically manage memory
- Improve application stability
- Reduce manual memory management
- Optimize heap usage
Garbage Collection Overview Diagram
Object Created
|
v
Object Used
|
v
Object Becomes Unreachable
|
v
Garbage Collector Detects Object
|
v
Memory Released
Why Java Uses Garbage Collection?
Unlike languages like C and C++, Java does not require manual memory deallocation.
C/C++ Example
free(memory);
Java Example
JVM automatically handles cleanup.
Where Does Garbage Collection Work?
Garbage Collection mainly works on:
Heap Memory
Heap Memory Diagram
Heap Memory
|
+-------> Young Generation
|
+-------> Old Generation
|
+-------> Metaspace
What Objects are Removed?
Objects that are:
- No longer reachable
- No longer referenced
Reachable Object Example
Employee emp =
new Employee();
Object is reachable because reference exists.
Unreachable Object Example
Employee emp =
new Employee();
emp = null;
What Happens Here?
Object becomes eligible for garbage collection.
Garbage Collection Internal Flow
Object Created in Heap
|
v
Reference Exists?
|
+-------> Yes → Keep Object
|
+-------> No → Remove Object
How Garbage Collector Detects Objects?
Garbage Collector uses:
- Reachability analysis
- Reference tracking
- Object graph traversal
Reference Graph Diagram
Root References
|
+-------> Reachable Objects
|
+-------> Unreachable Objects
|
v
Garbage Collected
Can We Force Garbage Collection?
We can request GC using:
System.gc();
Example
Employee emp =
new Employee();
emp = null;
System.gc();
Important Note
System.gc() only requests JVM.
Garbage Collection execution is NOT guaranteed immediately.
Why JVM Controls Garbage Collection?
Because JVM decides optimal cleanup timing based on:
- Memory pressure
- Heap usage
- Application performance
Types of Garbage Collectors
- Serial GC
- Parallel GC
- G1 GC
- ZGC
- Shenandoah GC
1. Serial Garbage Collector
Uses single thread for garbage collection.
Best For
- Small applications
- Low-memory systems
2. Parallel Garbage Collector
Uses multiple threads for faster garbage collection.
Best For
- Multi-core systems
- High throughput applications
3. G1 Garbage Collector
G1 (Garbage First) GC is modern JVM default collector.
Features
- Low pause times
- Better scalability
- Efficient heap management
4. ZGC
Low-latency garbage collector for very large heaps.
Best For
- Cloud-native systems
- Large enterprise applications
Young Generation and Old Generation
Heap memory is divided into generations.
Young Generation
Stores newly created short-lived objects.
Old Generation
Stores long-lived objects.
Generation Flow
New Object Created
|
v
Young Generation
|
+-------> Dies Quickly → Removed
|
+-------> Survives → Promoted
|
v
Old Generation
Minor GC
Garbage Collection in Young Generation.
Major GC
Garbage Collection in Old Generation.
Full GC
Cleans entire heap memory.
Why Full GC is Expensive?
Because application may pause during cleanup.
Stop-the-World Event
During some GC operations, application threads pause temporarily.
GC Pause Flow
Application Running
|
v
GC Starts
|
v
Threads Paused
|
v
Memory Cleanup
|
v
Application Resumes
What is Memory Leak in Java?
Memory leak occurs when objects remain referenced unnecessarily.
Example
Listemployees = new ArrayList<>(); while(true) { employees.add( new Employee() ); }
Problem
- Objects stay reachable forever
- GC cannot remove them
What is OutOfMemoryError?
Occurs when JVM cannot allocate additional heap memory.
Example Error
java.lang.OutOfMemoryError: Java heap space
Garbage Collection and finalize()
Before removing objects, GC may call:
finalize()
method.
Important Modern Note
finalize() is deprecated in modern Java.
Modern Cleanup Alternatives
- try-with-resources
- AutoCloseable
- Cleaner API
Garbage Collection in Banking Systems
Banking applications use GC for:
- Transaction object cleanup
- Session management
- Temporary data removal
- High-volume processing
GC in E-Commerce Systems
E-commerce systems use GC for:
- Shopping cart cleanup
- Order processing objects
- Inventory caching
- Temporary payment sessions
Garbage Collection in Spring Boot
Spring Boot applications rely heavily on GC because:
- REST requests create temporary objects
- JSON serialization creates objects
- Dependency injection creates beans
Spring Boot Example
@RestController
public class UserController {
}
Request processing creates temporary objects cleaned by GC.
Garbage Collection in Microservices
Microservices architectures require optimized GC for:
- Containerized environments
- High concurrency
- API gateways
- Kafka consumers
- Cloud-native scaling
Docker and JVM GC Tuning
Cloud deployments tune GC using:
-Xms512m -Xmx2g
Meaning
- Xms → Initial heap size
- Xmx → Maximum heap size
Modern GC Monitoring Tools
- JConsole
- VisualVM
- Java Flight Recorder
- Grafana
- Prometheus
GC Monitoring Flow
Application Running
|
v
GC Metrics Collected
|
v
Heap Usage Analyzed
|
v
Performance Optimized
Advantages of Garbage Collection
- Automatic memory cleanup
- Reduced manual memory handling
- Improved developer productivity
- Safer memory management
Disadvantages of Garbage Collection
- GC pauses may affect performance
- Memory leaks still possible
- Requires JVM tuning for large systems
Common Interview Mistake
Many developers think:
System.gc()
forces immediate garbage collection.
Actually:
- It only requests JVM.
Another Common Mistake
Many developers think Java completely prevents memory leaks.
Actually:
- Improper references can still create leaks.
Best Practices
- Remove unused references
- Avoid unnecessary object creation
- Use connection pooling
- Monitor heap memory regularly
- Use efficient collections carefully
Realtime Enterprise Example
REST API Request Processing
Incoming API Request
|
v
Temporary Objects Created
|
v
Request Completed
|
v
Garbage Collector Removes Objects
Related Learning Topics
- What is Memory Management in Java
- How JVM Works Internally
- What is String Pool in Java
- What is finalize() Method in Java
- What is Immutable Class in Java
- Why String is Immutable in Java
- Memory Management in Java
- What is Spring Boot
- What are Microservices
Professional Interview Answer
Garbage Collection in Java is the automatic process of identifying and removing unused objects from heap memory. The JVM Garbage Collector tracks object references and removes objects that are no longer reachable, helping optimize memory usage and prevent memory leaks. Java provides multiple garbage collectors such as Serial GC, Parallel GC, G1 GC, and ZGC for different performance requirements. Garbage Collection is a core part of Java memory management and is heavily used in enterprise systems, Spring Boot applications, banking platforms, cloud-native microservices, and distributed systems to ensure scalability, stability, and efficient resource utilization.
Frequently Asked Questions
What is Garbage Collection in Java?
Garbage Collection is the automatic process of removing unused objects from memory.
Where does Garbage Collection work?
Garbage Collection mainly works on heap memory.
Can we force Garbage Collection?
No, System.gc() only requests JVM for garbage collection.
What causes memory leaks in Java?
Unused objects that remain referenced cause memory leaks.
What is Full GC?
Full GC cleans entire heap memory including young and old generations.