Garbage collector (GC)

The garbage collector (GC) is the JVM subsystem that automatically reclaims memory held by objects no longer reachable from any live reference. It is why Java does not expose malloc/free or delete — memory management is the runtime's job.

What "reachable" means

An object is reachable if a chain of references connects it to a GC root: a local variable on the stack, a static field, an active thread, a JNI handle. Unreachable objects are garbage and can be freed.

Modern GCs in OpenJDK

GCDefault sinceFocus
G1GC (Garbage First)Java 9Low pause + throughput — default for most workloads
ZGCJava 15 (stable)Sub-millisecond pauses, very large heaps
ShenandoahJava 12Low pause, concurrent compaction
Parallel GCLegacyMax throughput, longer pauses
Serial GCLegacyTiny heaps, single-core environments

Tuning the GC

java -XX:+UseG1GC -Xmx4g -jar app.jar
java -XX:+UseZGC -Xmx16g -jar app.jar

For most applications, the default (G1GC) is correct. Tune only when profiling shows GC pauses are a problem.

What GC does NOT do

GC frees Java heap memory. It does not close files, sockets or native resources. For those, implement AutoCloseable and use try-with-resources.