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
| GC | Default since | Focus |
|---|---|---|
| G1GC (Garbage First) | Java 9 | Low pause + throughput — default for most workloads |
| ZGC | Java 15 (stable) | Sub-millisecond pauses, very large heaps |
| Shenandoah | Java 12 | Low pause, concurrent compaction |
| Parallel GC | Legacy | Max throughput, longer pauses |
| Serial GC | Legacy | Tiny 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.