Garbage collectors in Java automatically reclaim heap memory occupied by objects that are no longer reachable. Different garbage collectors use different strategies to balance application throughput, pause time, and memory usage.
- Memory reclamation occurs automatically, but its timing is determined by the JVM.
- Applications can select a garbage collector based on performance and latency requirements.
Example: Making an object eligible for garbage collection.
public class Geeks{
public static void main(String[] args){
String data = new String("Garbage Collection Demo");
// Remove the reference
data = null;
System.out.println("Object is eligible for garbage collection.");
}
}
Output
Object is eligible for garbage collection.
Explanation: Assigning null removes the reference held by data. If no other references keep the created String object reachable, it becomes eligible for garbage collection.
Note: The output indicates object eligibility, not actual garbage collection. The JVM determines when memory reclamation occurs.
Types of Garbage Collectors
HotSpot JVM provides several garbage collectors designed for different application workloads.
1. Serial Garbage Collector
Serial GC performs garbage collection using a single thread while pausing application threads.
- Suitable for small applications and environments with limited CPU resources.
- Avoids the coordination overhead associated with multiple GC threads.
Command:
java -XX:+UseSerialGC -jar Application.jar
2. Parallel Garbage Collector
Parallel GC uses multiple threads for garbage collection while pausing application threads. It is also known as the throughput collector.
- Suitable for applications that prioritize throughput over short pause times.
- Was the default collector on server-class machines in Java 8.
Command:
java -XX:+UseParallelGC -jar Application.jar
3. Garbage-First (G1) Garbage Collector
G1 GC divides the heap into regions and prioritizes old-generation regions that offer efficient memory reclamation.
- Balances application throughput and garbage collection pause times.
- Became the default collector on server-class machines in Java 9.
Command:
java -XX:+UseG1GC -jar Application.jar
4. Z Garbage Collector (ZGC)
ZGC is a low-latency garbage collector designed to perform most garbage collection work concurrently with application execution.
- Introduced experimentally in Java 11 and became production-ready in Java 15.
- Supports large heaps while targeting very short garbage collection pauses.
Note: Starting with Java 24, ZGC operates exclusively in generational mode.
Command:
java -XX:+UseZGC -jar Application.jar
5. Shenandoah Garbage Collector
Shenandoah is a low-latency collector that performs much of its work, including object relocation, concurrently with application threads.
- Introduced experimentally in Java 12 and became production-ready in Java 15.
- Suitable for latency-sensitive applications requiring short garbage collection pauses.
Command:
java -XX:+UseShenandoahGC -jar Application.jar
Its availability depends on the JDK distribution and supported platform.
6. Epsilon Garbage Collector
Epsilon is a no-operation garbage collector introduced in Java 11. It handles memory allocation without performing memory reclamation.
- Used for performance testing, benchmarking, and short-lived workloads with predictable memory requirements.
- Throws OutOfMemoryError when the available heap memory is exhausted and further allocation fails.
Command:
java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -jar Application.jar
7. Concurrent Mark-Sweep (CMS) Garbage Collector
CMS was designed to reduce pause times by performing much of its garbage collection work concurrently with application threads.
It was deprecated in Java 9 and removed in Java 14. The -XX:+UseConcMarkSweepGC option should not be used in modern JDK releases.
Configuring Garbage Collection
1. Controlling Garbage Collection Threads
The ParallelGCThreads option configures the number of parallel garbage collection worker threads for applicable collectors.
java -XX:+UseParallelGC -XX:ParallelGCThreads=4 -jar Application.jar
This command selects Parallel GC and configures four parallel GC worker threads.
2. Setting a Garbage Collection Pause-Time Goal
The MaxGCPauseMillis option specifies a target pause duration in milliseconds for supported collectors, such as Parallel GC and G1 GC.
java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -jar Application.jar
The garbage collector attempts to achieve a pause-time goal of 200 milliseconds. This is a performance target, not a guaranteed maximum pause duration.
Common JVM Memory and Garbage Collection Options
Option | Description |
|---|---|
-Xms<size> | Sets the initial heap size. |
-Xmx<size> | Sets the maximum heap size. |
-XX:MaxMetaspaceSize=<size> | Limits native memory allocated for class metadata. |
-XX:+HeapDumpOnOutOfMemoryError | Enables heap dump generation for supported out-of-memory failures. |
-XX:HeapDumpPath=<path> | Specifies the heap dump file or directory. |
-Xlog:gc | Enables basic garbage collection logging. |
-Xlog:gc* | Enables more detailed garbage collection logging. |
-XX:ParallelGCThreads=<n> | Configures the number of parallel GC worker threads for supported garbage collectors. |
-XX:ConcGCThreads=<n> | Configures concurrent GC worker threads for applicable collectors. |
-XX:MaxGCPauseMillis=<n> | Sets a garbage collection pause-time goal in milliseconds. |
-XX:G1HeapRegionSize=<size> | Configures the heap region size for G1 GC. |
-XX:+UseContainerSupport | Enables container resource detection on supported platforms. |
Note: JVM options and collector availability depend on the JDK version, distribution, and platform. Unified logging options such as -Xlog:gc were introduced in Java 9.
Comparison of Garbage Collectors
Collector | Primary Objective | Collection Behavior | Suitable For |
|---|---|---|---|
Serial GC | Low GC coordination overhead | Single-threaded, stop-the-world | Small applications |
Parallel GC | High throughput | Multithreaded, stop-the-world | Batch processing |
G1 GC | Balance throughput and latency | Parallel and concurrent phases | General-purpose applications |
ZGC | Very low latency | Mostly concurrent | Large heaps and latency-sensitive applications |
Shenandoah GC | Low pause times | Mostly concurrent | Latency-sensitive applications |
Epsilon GC | Eliminate GC reclamation overhead | No memory reclamation | Testing and benchmarking |
CMS GC | Low pause times | Mostly concurrent | Legacy applications; removed in Java 14 |