Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Language Features by Version

Java garbage collection

How Java garbage collection works: reachability, generations, and a comparison of the Serial, Parallel, G1, ZGC and Shenandoah collectors with their flags.

Java frees memory automatically. The garbage collector (GC) finds objects that the program can no longer reach and reclaims their space, so there is no free() and no dangling pointer. You still decide how many objects to create and how long to hold on to them, and you can choose which collector the JVM uses.

An object is garbage when no chain of references leads to it from a GC root: a local variable on a live thread's stack, a static field of a loaded class, a JNI reference or similar. Cycles do not matter. Two objects that point at each other but are unreachable from any root are both collected.

Java
Object o = new Object();   // reachable through the local variable o
o = null;                  // now eligible for collection (no one decides exactly when)

Generations and phases

Most objects die young, so most HotSpot collectors keep young and old regions. New objects are allocated in the young area; a minor collection copies the survivors out and discards the rest. Objects that survive several rounds are promoted to the old area, which is collected less often by a major or mixed collection. Collectors differ in how much of the work they do while the application is paused (stop-the-world) and how much runs concurrently with it.

The collectors

Collector Flag Best for Notes
Serial -XX:+UseSerialGC Tiny heaps, single CPU, small containers One thread, simplest, lowest overhead
Parallel -XX:+UseParallelGC Batch jobs where throughput matters most Multiple GC threads, pauses scale with heap
G1 -XX:+UseG1GC General purpose; the default on multi-core machines with at least about 1.8 GB since Java 9 Region-based, aims at a pause-time goal (-XX:MaxGCPauseMillis)
ZGC -XX:+UseZGC Large heaps and very low latency Concurrent; pauses stay short regardless of heap size; generational and the default mode since Java 23
Shenandoah -XX:+UseShenandoahGC Low latency Concurrent compaction; available in OpenJDK builds that include it
Epsilon -XX:+UseEpsilonGC Tests and very short-lived programs Allocates but never frees

The JVM picks Serial automatically when it believes it runs on a "client-class" machine (fewer than two CPUs or less than about 1.8 GB), which is the case in the sandbox on this page. The earlier Concurrent Mark Sweep (CMS) collector was removed in Java 14.

Try it

Java Garbage is reclaimed, cycles included

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Strong, soft, weak and phantom references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Reference types

Type Cleared when Typical use
Strong (ordinary reference) never while reachable everything
SoftReference the JVM is short of memory memory-sensitive caches
WeakReference the next collection after no strong refs remain canonicalizing maps, WeakHashMap
PhantomReference after the object is finalized, get() always returns null cleanup actions; Cleaner is the easier API

Reading GC logs (read-only)

Terminal
# Read-only: unified logging, Java 9+
java -Xlog:gc MyApp
java -Xlog:gc*:file=gc.log:time,uptime,level,tags MyApp

A line such as Pause Young (Normal) ... 24M->4M(256M) 3.1ms says a young collection shrank used memory from 24 MB to 4 MB within a 256 MB heap and paused the program for about 3 ms.

Usage notes

  • Tune last. Fix allocation hot spots and leaks first. Switching collectors helps less than creating fewer objects.
  • Pick by goal. Throughput (batch): Parallel. Balanced default: G1. Tail latency on big heaps: ZGC. Tiny containers: Serial.
  • Do not rely on finalize(). It is deprecated for removal since Java 18 and may be disabled entirely. Use try-with-resources and AutoCloseable, or Cleaner as a safety net.
  • System.gc() is advisory. The JVM may ignore it (-XX:+DisableExplicitGC). Never use it for program logic.
  • Large allocation rates cost pause time, not just heap. Avoid boxing in tight loops and building many short strings.
  • Soft references are a poor cache. Their clearing policy depends on JVM heuristics; use a bounded cache with explicit eviction instead.
  • Heap size trade-off. A bigger heap means fewer collections but, for non-concurrent collectors, longer individual pauses.