Garbage Collection (GC) in Java is an automatic memory management process. The JVM uses different GC algorithms to reclaim unused objects, optimize memory usage, and minimize application pause times.
GC algorithms are selected using JVM flags. Each algorithm has different behavior in terms of pause time, memory usage, and CPU overhead.
// Example JVM options to enable G1 Garbage Collector
java -XX:+UseG1GC -Xms512m -Xmx1024m -jar app.jar
// Simple Java program to create objects and trigger GC
public class GCExample {
public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
byte[] data = new byte[1024 * 1024];
}
System.out.println("Objects created");
}
}
Visualize the "Mark and Sweep" process. Allocate memory, then run GC to free up "dead" objects.
Heap is empty
When the program runs with GC logging enabled, the JVM prints information about memory allocation and garbage collection cycles.
Using -Xlog:gc helps analyze GC behavior in real applications.