Garbage Collection (GC) is a critical component of the Java Virtual Machine (JVM) that automatically manages memory by identifying and reclaiming objects no longer in use. Understanding garbage collection is essential for building high-performance Java applications, especially those with strict latency requirements or handling large data volumes.
This comprehensive guide explores Java garbage collection in depth, covering:
Java memory is divided into several key areas:
Traditional Java garbage collectors use a generational approach based on the observation that most objects die young ("Weak Generational Hypothesis").
Generation | Purpose | Collection Frequency |
---|---|---|
Young Generation (Eden + Survivor spaces) | Newly created objects | Frequent (Minor GC) |
Old Generation (Tenured) | Long-lived objects promoted from Young Generation | Less frequent (Major GC) |
The typical object lifecycle follows this pattern:
The simplest collector, using a single thread for both minor and major collections.
java -XX:+UseSerialGC -Xms1g -Xmx1g MyApplication
Best for: Small applications with limited memory requirements and running on devices with single or dual-core processors.
Uses multiple threads for collection, maximizing throughput but still causing stop-the-world pauses.
java -XX:+UseParallelGC -XX:ParallelGCThreads=4 -Xms4g -Xmx4g MyApplication
Best for: Batch processing applications that prioritize throughput over latency.
Default since Java 9, G1GC is a server-style collector designed for multi-processor machines with large memories.
java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -Xms4g -Xmx4g MyApplication
Key features:
Low-latency collector designed for very large heaps with pause times under 10ms.
java -XX:+UseZGC -Xms8g -Xmx8g MyApplication
Key features:
Another low-latency collector similar to ZGC but with different implementation details.
java -XX:+UseShenandoahGC -Xms4g -Xmx4g MyApplication
# Basic heap size settings
-Xms # Initial heap size
-Xmx # Maximum heap size
# Example
-Xms4g -Xmx4g # Fixed heap size (recommended for production)
-Xms1g -Xmx4g # Growing heap (less predictable)
# Young generation sizing
-XX:NewRatio=n # Ratio of old to young generation
-XX:NewSize=n # Initial young generation size
-XX:MaxNewSize=n # Maximum young generation size
-Xmn # Shorthand for setting both NewSize and MaxNewSize
# G1GC pause time goal
-XX:MaxGCPauseMillis=200 # Target pause time in milliseconds
# Initiating heap occupancy
-XX:InitiatingHeapOccupancyPercent=45 # Percentage of heap that triggers concurrent marking
Enable detailed GC logging to understand collection behavior:
# Java 8
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:/path/to/gc.log MyApplication
# Java 9+
java -Xlog:gc*=info:file=/path/to/gc.log:time,uptime,level,tags MyApplication
// Generate a heap dump
jmap -dump:format=b,file=heapdump.hprof <pid>
// Enable automatic heap dumps on OutOfMemoryError
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dumps MyApplication
Requirement | Recommended Collector |
---|---|
Maximum throughput | Parallel GC |
Balanced throughput/latency | G1GC |
Minimum latency | ZGC/Shenandoah |
Small footprint | Serial GC |
Running Java applications in containers requires special consideration for memory settings:
# Enable container support (automatic in Java 11+)
java -XX:+UseContainerSupport
# Set memory as percentage of container memory instead of fixed values
java -XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=75.0
Some data structures create less GC pressure:
Understanding Java garbage collection is crucial for optimizing application performance, especially in production environments. The JVM offers several garbage collection algorithms, each with its own strengths and appropriate use cases. By selecting the right collector, tuning key parameters, and following best practices, you can significantly improve application performance and stability.
Remember that garbage collection is an ongoing concern rather than a one-time optimization. Monitor your application's GC behavior, analyze patterns, and adjust settings as your application evolves and usage patterns change.