GC roots and collectors
What you will learn
Garbage collection reclaims storage according to reachability rules. It does not know which still-reachable objects your business logic no longer needs.
- Trace reachability from roots.
- Contrast strong, soft, weak and phantom references.
- Choose collector evaluation criteria without universal tuning claims.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only trusted local classes and fixed synthetic data. Never run these diagnostics against another person’s process. The runner enforces a process deadline.
Clear a weak reference explicitly
public class Main {
public static void main(String[] args) throws Exception { Object value = new Object(); var ref = new java.lang.ref.WeakReference<>(value); System.out.println(ref.refersTo(value)); ref.clear(); System.out.println(ref.get() == null); java.lang.ref.Reference.reachabilityFence(value); }}Expected output:
truetrueExplicit clear changes the reference, not the strong local. This test makes no assertion about collector timing.
Reachability model
Imagine a root such as a live thread reference or a reachable static field pointing to A, which points to B. B stays strongly reachable while the path exists. An isolated cycle C ↔ D can be collected even though the two refer to each other. GC roots are implementation-level starting points, also including relevant JNI references. Removing a reference may make an object eligible for collection, not force collection.
Reference strengths
Ordinary references keep a reachable object strongly reachable. SoftReference allows memory-sensitive retention under collector policy, not a reliable bounded cache. WeakReference permits collection when the referent is only weakly reachable. PhantomReference.get() always returns null; a queue can notify code after phantom reachability processing, but notification is not a deterministic resource lifecycle. ReferenceQueue.poll() returns null if empty. Explicit enqueue clears and queues a reference; it does not demonstrate GC. Reference.reachabilityFence keeps an object strongly reachable until the fence. Prefer try-with-resources to finalization or GC-dependent cleanup.
Collector trade-offs
Serial uses a single GC worker and can suit small workloads. Parallel uses multiple GC workers for throughput. G1 is region-based and generational, performs much work concurrently, and aims for pause targets, not strict deadlines. ZGC emphasizes short pauses with concurrent work and is generational in Java 25; Java 21 also offers non-generational ZGC. Collector availability and defaults depend on distribution, version and hardware. Compare latency percentiles, application throughput, CPU and memory headroom under representative workload; a small lab is not a benchmark. -Xlog:gc reports HotSpot GC logging; no log line alone proves a particular object has been reclaimed.
Observe an explicit queue notification
public class Main {
public static void main(String[] args) throws Exception { var queue = new java.lang.ref.ReferenceQueue<Object>(); Object value = new Object(); var ref = new java.lang.ref.WeakReference<>(value, queue); System.out.println(queue.poll() == null); System.out.println(ref.enqueue()); System.out.println(queue.poll() == ref); java.lang.ref.Reference.reachabilityFence(value); }}Expected output:
truetruetrueThe program enqueues explicitly while retaining the object. A real GC notification can arrive asynchronously.
Compare soft and phantom access
public class Main {
public static void main(String[] args) throws Exception { Object value = new Object(); var soft = new java.lang.ref.SoftReference<>(value); var phantom = new java.lang.ref.PhantomReference<>(value, new java.lang.ref.ReferenceQueue<>()); System.out.println(soft.get() == value); System.out.println(phantom.get() == null); java.lang.ref.Reference.reachabilityFence(value); }}Expected output:
truetrueSoft access is available here because value is strongly reachable; a phantom never exposes its referent through get.
Common mistakes
Never use System.gc(), sleeps or allocating until failure to demand a particular collection. Do not treat weak keys or soft references as a strict capacity policy.
Practice
Create a weak reference registered with a queue. Explicitly enqueue it, verify the reference is cleared and the queue returns that same reference. Print true twice. Keep the referent reachable until the check.
Expected output:
truetrueCompare your answer with the manual practice criteria.
Official reading: References · Reference · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
GC roots and collectors — knowledge check
Original memory and diagnostics questions.
Can an isolated cycle be collected?
What does PhantomReference.get return?
What does explicit enqueue establish?
Which collector emphasizes short pauses with concurrent work?
Does a G1 pause target guarantee every pause duration?