Garbage Collection (GC) in Java is a process by which the Java Virtual Machine (JVM) automatically identifies and removes unused objects from memory, freeing up resources and preventing memory leaks. This process is a key feature of Java’s memory management system, which eliminates the need for manual memory management by the programmer.
Key Features of Garbage Collection
- Automatic Memory Management:
- Java handles memory allocation and deallocation automatically.
- Programmers do not need to explicitly free memory.
- Non-Deterministic:
- The exact timing of garbage collection is not predictable.
- It occurs when the JVM decides it is necessary, such as when memory is low.
- Managed Heap Memory:
- Objects are created in the heap.
- Garbage collection cleans up the heap by removing objects no longer in use.
How Garbage Collection Works
- Object Lifecycle:
- Objects are created on the heap using new.
- Objects become eligible for garbage collection when no active references exist to them.
- Eligibility for Garbage Collection:
- An object is eligible for garbage collection if it is unreachable.
- Unreachable means no live thread can access it.
- Reference Counting and Reachability Analysis:
- JVM uses a technique called reachability analysis to determine if an object is no longer referenced.
- If an object is not reachable from the GC roots, it is considered garbage.
GC Roots
The following references are considered GC roots:
- References from active threads.
- References from static variables.
- References from method-local variables in the stack.
- References from JNI (Java Native Interface) handles.
Garbage Collection Process
Mark-and-Sweep Algorithm
- Mark Phase:
- All reachable objects are marked as alive.
- Sweep Phase:
- Unmarked objects are considered garbage and are removed.
- Memory occupied by these objects is reclaimed.
JVM Garbage Collectors
The JVM offers several garbage collectors optimized for different use cases. Examples include:
- Serial GC:
- Designed for single-threaded applications.
- Uses a simple mark-and-sweep algorithm.
- Parallel GC:
- Uses multiple threads for garbage collection.
- Suitable for multi-threaded applications.
- Concurrent Mark-Sweep (CMS) GC:
- Minimizes pause times by performing GC concurrently with application threads.
- Ideal for applications requiring low latency.
- G1 GC (Garbage-First Garbage Collector):
- Divides the heap into regions.
- Prioritizes collecting regions with the most garbage first.
- Suitable for large heaps and applications with low-latency requirements.
- ZGC (Z Garbage Collector):
- Designed for sub-millisecond pause times.
- Works well for very large heaps.
Example of Garbage Collection
Code Example: Object Eligibility for GC
public class GarbageCollectionDemo {
public static void main(String[] args) {
// Object 1: Eligible for GC
String str = new String(“Hello”);
str = null; // Reference is removed, eligible for GC
// Object 2: Not eligible for GC
GarbageCollectionDemo obj = new GarbageCollectionDemo();
}
}
Calling Garbage Collector
Java allows invoking the garbage collector using:
System.gc();
Runtime.getRuntime().gc();
Note: These methods are merely suggestions to the JVM. Garbage collection is still not guaranteed to run immediately.
Example:
public class Main {
public static void main(String[] args) {
Main obj = new Main();
obj = null; // Make the object eligible for GC
System.gc(); // Request garbage collection
System.out.println(“Garbage collection requested.”);
}
@Override
protected void finalize() {
System.out.println(“Finalize method called.”);
}
}
The finalize() Method
- Before an object is removed by GC, the JVM calls its finalize() method.
- This method can be overridden to release resources before the object is collected.
- Deprecated: The use of finalize() is discouraged because it is unpredictable and can cause performance issues.
Advantages of Garbage Collection
- Automatic Memory Management:
- Reduces the risk of memory leaks and dangling pointers.
- Simplifies Development:
- Developers do not need to explicitly manage memory allocation and deallocation.
- Improved Application Stability:
- Avoids crashes caused by improper memory handling.
Limitations of Garbage Collection
- Non-Deterministic:
- The exact timing of GC cannot be controlled, leading to potential performance issues during critical operations.
- Overhead:
- GC introduces additional CPU overhead.
- Not Foolproof:
- Memory leaks can still occur if references are unintentionally retained (e.g., in static variables).
Best Practices for Efficient Garbage Collection
- Avoid Object Creation in Loops:
- Reuse objects when possible to minimize unnecessary object creation.
- Release References:
- Nullify references when objects are no longer needed.
- Use WeakReference or SoftReference:
- For objects that can be recreated or are not critical.
- Choose the Right Garbage Collector:
- Select a GC type that suits the application’s performance and latency requirements.
Conclusion
Garbage collection in Java is a powerful feature that simplifies memory management by automatically reclaiming unused memory. While it provides significant advantages, understanding its behavior and working within its constraints is essential to optimize application performance and avoid memory-related issues.