Garbage Collection: The Janitor

Garbage Collection: The Janitor in Java: Picture a busy harbour. Boats are tied up all along the quay, and the only thing keeping any boat from drifting out to…

The Analogy:

Picture a busy harbour. Boats are tied up all along the quay, and the only thing keeping any boat from drifting out to sea is a mooring line that ultimately traces back to the solid stone of the quay itself. Some boats are tied directly to a bollard. Others are rafted up -- tied to a boat that is tied to a boat that is finally tied to the quay. As long as you can follow an unbroken chain of lines from the quay to a boat, that boat stays put. The quay is the fixed anchor point everything must connect to.

Java's heap is that harbour, and the objects are the boats. The quay is a set of GC roots -- the local variables in methods that are currently running, the static fields, the live threads. An object is kept alive for exactly as long as the collector can trace a chain of references from some root to it. This is called being reachable. The garbage collector is the harbour master who periodically looks over the water, works out which boats are still connected to the quay, and clears away everything that is not.

Here is the insight that trips up people coming from other mental models: the harbour master does not count how many lines are tied to each boat. They trace outward from the quay. So two boats rafted only to each other -- each tied firmly to the other, but with no line reaching the quay -- are both adrift, and both get cleared, no matter how tightly they are lashed together. In Java terms, two objects that reference each other but that nothing reachable points to are an island of isolation, and the collector reclaims them both. This is why Java can collect cycles that a naive reference-counting scheme never could: it asks "reachable from a root?", not "does anything point at it?".

The failure mode is the boat you meant to release but whose line is still quietly tied to a bollard you forgot about. You are done with it, you think of it as gone -- but one forgotten line to the quay keeps it fully moored, and the harbour master will never touch it. Leave enough of these and the harbour fills up with boats nobody wants until there is no room for new arrivals. That is a Java memory leak: an object you are finished with, still reachable through some reference you forgot to drop -- a static list, a cache, an un-removed listener -- accumulating until the heap is exhausted and the program dies with OutOfMemoryError. In a garbage-collected language, leaks are not about forgetting to free; they are about forgetting to let go.

Syntax or Core Structure

import java.lang.ref.WeakReference;

public class Reachable {
    public static void main(String[] args) {
        Object kept = new Object();                     // a strong reference (a mooring line)
        WeakReference<Object> weak = new WeakReference<>(kept);

        System.gc();  // a request for a full collection -- the JVM may honour or ignore it

        // 'kept' is strongly reachable, so the object CANNOT be collected, gc or no gc:
        System.out.println("weak ref still resolves: " + (weak.get() != null));
        System.out.println("strong ref still held:   " + (kept != null)); // keeps 'kept' reachable here
    }
}

Output:

weak ref still resolves: true
strong ref still held:   true

This output is guaranteed on every run and every JVM. A WeakReference does not keep its target alive; weak.get() would return null once the object were collected. But here kept is a live strong reference, so no collection -- forced or not -- may reclaim the object, and weak.get() therefore resolves. The second line is not decoration: referencing kept after the gc() call is what proves it is still reachable across that call, since the JVM is allowed to reclaim a local's object the moment nothing uses it again.

Technical Depth:

Reachability From Roots, Not Reference Counting

The whole model rests on one rule: an object lives if and only if it is reachable by some chain of references starting at a GC root. Roots are the things the program is definitely still using -- variables in active method frames, static fields, running threads. Everything reachable from them is live; everything else, however tangled its internal references, is garbage. Setting the last reference to an object to null, letting a variable go out of scope, or reassigning it, all sever a link and may leave an object unreachable.

SituationReachable from a root?Collector's verdict
A local variable in a running method points to itYesKept
Only an already-unreachable object points to itNoEligible
Two objects point at each other, nothing else doesNo (an island)Both eligible -- cycles are collected
A static field points to itYes (a root)Kept for the field's whole lifetime

That last row is the leak factory. A static field is a root, so anything it holds -- and everything that holds -- stays alive for as long as the class is loaded, which is usually the life of the whole program. A cache in a static map that never evicts is the textbook example: every entry is permanently reachable, so the collector, correctly, never reclaims any of it.

One Null Is Not Enough

A common misreading is that setting a variable to null frees the object. It does not -- it removes one line to the quay. An object is eligible only when every strong reference to it is gone. If two variables point at the same object, nulling one leaves the object fully moored by the other.

import java.lang.ref.WeakReference;

public class OneNull {
    public static void main(String[] args) {
        Object obj = new Object();
        Object alias = obj;                          // TWO strong references to ONE object
        WeakReference<Object> weak = new WeakReference<>(obj);

        obj = null;    // drop one reference...
        System.gc();   // ...but 'alias' still moors the object, so it is NOT eligible

        System.out.println("survives one null: " + (weak.get() != null));
        System.out.println("alias still holds: " + (alias != null));
    }
}

Output:

survives one null: true
alias still holds: true

Because alias is still a live strong reference, the object cannot be collected, and weak.get() resolves -- guaranteed. Only when alias is also dropped (or goes out of scope) does the object finally become unreachable. This is why hunting a leak means finding every path from a root, not just the reference you were thinking of.

Generations, Reference Types, And Hands-Off Timing

Real collectors exploit a well-observed fact called the weak generational hypothesis: most objects die very young. So the heap is split into a young generation, where new objects are born and a cheap, frequent minor GC sweeps away the many that die fast, and an old generation, where the few long-lived survivors are promoted and collected only by a rarer, costlier major GC. This is why churning through many small, short-lived objects is cheap on a modern JVM -- they never leave the young generation. Between strong and unreachable there is also a spectrum of deliberately weaker references, each telling the collector how hard to hold on.

Reference typeKeeps object alive?Cleared whenTypical use
Strong (normal)Yes, alwaysOnly once unreachableOrdinary references
SoftYes, until memory is tightUnder memory pressureMemory-sensitive caches
WeakNoAt the next GC that finds only weak refsWeakHashMap, canonical maps
PhantomNoAfter finalization, via a ReferenceQueuePost-mortem cleanup

The one thing you do not get to control is when collection happens. System.gc() is only a suggestion the JVM is free to ignore, and calling it in production usually hurts: you may force an expensive full collection at exactly the wrong moment. Trust the collector's timing; your job is to make sure objects you are finished with actually become unreachable, not to schedule the sweep.

Real World Example:

import java.util.*;

public class SessionCache {
    // A static map is a GC root: everything it holds stays reachable for the program's life.
    static final Map<Integer, byte[]> cache = new HashMap<>();

    static void handle(int requestId) {
        cache.put(requestId, new byte[1024]); // cache the result... and never remove it
    }

    public static void main(String[] args) {
        for (int id = 1; id <= 5; id++) {
            handle(id);
        }
        System.out.println("entries retained: " + cache.size());
        System.out.println("all reachable via the static map, so none is collectable");
    }
}

Output:

entries retained: 5
all reachable via the static map, so none is collectable

This is what a memory leak looks like in a garbage-collected language: not a missing free, but a reference that outlives its usefulness. Each call to handle stashes a 1 KB array in a static map and never takes it out. The cache.size() of 5 is deterministic here because we made exactly five calls, but the point is what happens over time: in a real server, requestId climbs forever, the map grows without bound, and because a static field is a GC root, every array in it stays reachable and therefore un-collectable. The collector is working perfectly -- that is precisely the problem. It cannot reclaim what the program is still, technically, holding.

The reason this is so insidious is that nothing here is a bug in the ordinary sense. The code compiles, runs, passes tests, and behaves beautifully in a short demo. The leak only manifests under sustained load, as a slow climb in old-generation usage that ends, hours or days later, in an OutOfMemoryError whose stack trace points nowhere near the actual cause. Diagnosing it means capturing a heap dump and hunting for which root is retaining objects that should be dead.

The fixes all amount to letting go on purpose. Give the cache a bound and an eviction policy -- a LinkedHashMap in access-order mode as an LRU, or a purpose-built cache like Caffeine -- so old entries are removed as new ones arrive. Where the entries should live only as long as their keys are used elsewhere, a WeakHashMap lets the collector drop them automatically once the key is otherwise unreachable. The honest caveat is that weak and soft references are not a free "leak-proof" switch: a WeakHashMap whose keys are held strongly somewhere else still never clears, and soft references can bloat the heap right up to the memory limit before yielding, hurting latency. The real cure is deliberate lifecycle management -- deciding, explicitly, when each thing is no longer needed and severing its last reference.

Common Mistakes

  1. Calling System.gc() to "free memory". It is a suggestion the JVM may ignore, and when honoured it often forces an expensive full collection at a bad moment, hurting performance. Let the collector decide when to run.
  1. Believing GC prevents all memory leaks. GC reclaims unreachable objects. An object you forgot to stop referencing is still reachable and never collected. Leaks in Java are lingering references, not un-freed memory.
  1. Hoarding objects in a static collection. A static field is a GC root, so a static list or map that only ever grows retains everything it holds for the life of the program. Bound it and evict, or it becomes an unbounded leak.
  1. Forgetting to deregister listeners and callbacks. Registering an object as a listener creates a reference from the event source to it. If the source outlives the listener's usefulness and you never remove it, the listener -- and all it holds -- cannot be collected.
  1. Assuming an object dies the instant its variable goes out of scope. Eligibility and actual collection are different events. The object becomes eligible when unreachable; when it is reclaimed is up to the collector, and may be much later or, if memory is plentiful, not for a long time.
  1. Relying on finalize() for cleanup. Finalizers run at an unpredictable time, may never run at all, and are deprecated. Release resources with try-with-resources and AutoCloseable, not by hoping a finalizer fires.
  1. Thinking cyclic references cause leaks. They do not in Java. A cycle unreachable from any root is collected in full. This intuition is imported from reference-counting systems and does not apply to a tracing collector.
  1. Nulling out local variables "to help GC". Setting a local to null at the end of a method is almost always pointless -- the frame is about to disappear anyway -- and clutters code. It matters only for a long-lived field or a genuinely long-running method holding a large object.
  1. Misusing weak or soft references as a leak cure-all. A WeakHashMap whose keys are still strongly reachable elsewhere never clears, and soft references can hold the heap near its limit. They are precision tools for specific lifecycles, not a blanket fix.

Best Practices

  • Trust the collector's timing. Do not call System.gc() in production. Focus your effort on making finished objects unreachable, and leave the scheduling of collection to the JVM, which has far more information than you do.
  • Bound every cache. Any structure that accumulates entries needs a size limit and an eviction policy -- an LRU via LinkedHashMap, or a library like Caffeine. An unbounded cache is a leak with a friendly name.
  • Let go of references you are done with. Remove listeners when they are no longer needed, clear entries from long-lived collections, and scope objects as narrowly as possible so they fall out of reach naturally.
  • Prefer short-lived objects; do not fear them. The young generation makes allocating and discarding many small, temporary objects cheap. Write clear code with local objects rather than pooling everything out of a misplaced fear of GC.
  • Use try-with-resources for cleanup, never finalizers. Deterministic release of files, sockets, and connections belongs in AutoCloseable and a try-with-resources block, whose timing you control -- unlike finalization, whose timing you do not.
  • Reach for weak and soft references deliberately. Use a WeakHashMap for entries that should vanish with their keys, and soft references for genuinely memory-sensitive caches -- but only after understanding exactly when each is cleared.
  • Diagnose leaks with the right tools. When old-generation usage climbs steadily, capture a heap dump and use a profiler (VisualVM, JFR, an MAT analysis) to find the retaining root, rather than guessing or sprinkling System.gc().
  • Match the collector to the workload. For latency-sensitive services, know that low-pause collectors (G1, ZGC, Shenandoah) exist and are chosen with JVM flags. The default is a good general choice, but the collector is tunable when a real need is measured.

Practice Exercises

  1. The GC Request: Write a loop that creates a million short-lived objects, then call System.gc() and print Runtime.getRuntime().freeMemory() before and after. Observe that the numbers move, but also that they vary run to run -- and note in a comment why you would not rely on System.gc() in real code.
  1. Soft vs Weak: Research WeakReference. Create one wrapping an object, keep a strong reference too, and confirm weak.get() is non-null. Then drop the strong reference, and explain why the weak reference now permits collection where the strong one forbade it.
  1. The Monitoring: Look up the memory graph in VisualVM or JConsole. Describe the "zig-zag" sawtooth pattern -- memory climbing as objects are allocated, then dropping sharply at each collection -- and explain what a steadily rising lower edge of that zig-zag would tell you about a possible leak.