Lesson · Object Initialization & Memory
Object lifecycle: from new to unreachable
16 min readObject Lifecycle
Every object runs the same arc: allocated, reachable, unreachable, reclaimed. Garbage collection handles the memory; the interesting failures are the places where something keeps reaching an object you thought was gone.
The leak with no villain
A service keeps a record of everything it processes. Traffic stops; memory does not:
static final List<Order> processed = new ArrayList<>(); void handle(Order order) { processed.add(order); // 'keep a record for later' } // nothing ever removes: the list only grows
Predict: every local reference to each order is long gone, so why is the memory not? One static list still reaches every order ever handled. Garbage collection is not about whether you meant to keep something; it is about whether anything can still reach it.
The arc every object walks
From the collector's point of view, every object is in exactly one of four stages:
| Stage | What is true | Who drives it |
|---|---|---|
| Created | Heap allocated, zeroed, constructed; reachable through the new expression | new |
| In use | Reachable from GC roots: live frames, static fields, references between objects | Your code |
| Unreachable | No chain of references from any root leads to it | Your code, by dropping the last reference |
| Collected | The memory is reclaimed; no reference can bring it back | The collector, whenever it runs |
Reachability is the entire contract. The moment the last chain from a root breaks, the object is on death row; when the collector next runs, the memory is reusable. Nothing else about the object matters.
Roots, chains, and cycles
The reachability question is answered by walking reference chains from a small starting set:
- Roots: stack frames of live threads (their locals and parameters), static fields, JNI handles.
- Chains: root to field to field. Any path keeps the object alive; no path means collectable.
- Cycles are fine: tracing collectors do not count references, so two objects pointing at each other with no root path are collected together.
- `System.gc()` is a request: it does not force collection, and no correct program depends on when collection happens.
A memory leak in Java is not lost memory; it is memory still reachable that no longer serves a purpose. The fix is always at the retaining path, never at the collector.
Object lifecycle · who still reaches it
GC roots
Heap
no objects
main() has started: roots exist (the frame and the static field) but they reach nothing yet.
Choosing reference strength
Java offers four strengths of reference, and the choice is a design decision about what losing the object would mean:
| Reference | Keeps the object alive? | Typical use |
|---|---|---|
| Strong (the normal kind) | Yes, until the reference itself goes away | Everything ordinary |
| Soft | Until memory pressure; the collector may clear it | Memory-sensitive caches |
| Weak | No: cleared once only weak references remain | Caches, listener registries, canonical maps |
| Phantom | No: used to observe collection | Cleanup scheduling, as in Cleaner |
A cache that answers 'would it be wrong to lose this?' with 'no' should hold weak or soft references, not strong ones. Strong entries are exactly how caches become leaks.
Finding and preventing leaks
The patterns that keep objects reachable forever, and the tools that expose them:
- The usual suspects: unbounded collections, static caches, listeners never removed, ThreadLocal values left in pooled threads.
- Diagnosis: heap dumps (jmap, JFR, IDE profilers) show the retaining path back to a root; dominator views rank who holds the most.
- Prevention: bounded caches with eviction, weak references where losing the entry is acceptable, an explicit remove paired with every add.
- Resources are not memory: files, sockets and locks need deterministic cleanup with try-with-resources, because the collector provides no guaranteed moment.
The GC reclaims memory, never correctness. Resources have close(), sessions have endings, and the collector's only promise is that unreachable memory becomes reusable eventually.
The lifecycle playbook
When memory climbs, or before it does, in order:
- Ask who still reaches the object: walk from roots (frames, statics) through fields until a path appears or does not.
- If the answer is 'a collection that only grows', that is the leak: bound it, evict from it, or weaken it.
- Pair every registration with an unregistration; listeners and subscriptions outlive their creators surprisingly often.
- For resources, do not wait for collection at all: try-with-resources closes deterministically on every path.
Allocated, reachable, unreachable, reclaimed. Objects leave by reachability, resources leave by close(), and mixing the two up is where production incidents live.
finalize is deprecated; Cleaner is the modern answer
finalize() promised a last-chance hook before collection, but it ran unpredictably, at most once, and could resurrect objects, so it is deprecated. When post-mortem cleanup is genuinely unavoidable, java.lang.ref.Cleaner (built on phantom references) does the job off the critical path, without waking the object from the dead. For anything with a real close() contract, try-with-resources beats both.
Interview angles
When is an object eligible for garbage collection?+
When no chain of strong references from GC roots (live frames, static fields, JNI handles) can reach it.
Eligibility is not collection: the collector runs on its own schedule, so an eligible object may linger. Tracing from roots also means cycles need no special handling at all.
Object o = new Object(); o = null; // eligible, not collected
Common misconception: That nulling the last variable collects immediately. It only removes the reference; collection is a later, unscheduled event.
Follow-up: What does System.gc() guarantee?
Do reference cycles leak in Java?+
No. Tracing collectors care about reachability from roots, not about reference counts between objects.
Two objects pointing at each other with no root path are collected together. Cycles only matter when something inside the cycle is still reachable, which is a different problem: an ordinary retention bug.
class Node { Node next; } a.next = b; b.next = a; // a cycle: collected once both are unreachable
Common misconception: That Java needs special support to collect cycles, or that a cycle alone is a leak.
Follow-up: When does a reference cycle actually cause trouble?
When would you use a WeakReference?+
When holding the object strongly would be wrong: caches that must not keep entries alive, listener registries that must not prevent collection.
WeakHashMap and weak listener lists are the standard patterns, with reference queues to learn when an entry clears. Soft references sit in between: cleared under memory pressure, useful for caches that would like to keep data while memory allows.
WeakReference<Image> preview = new WeakReference<>(image); // this cache does not keep image alive
Common misconception: That a weak reference is a safety net. One strong reference anywhere else defeats it completely.
Follow-up: Why is SoftReference a poor choice for correctness-critical logic?
What is the difference between a resource and memory?+
Memory is reclaimed whenever the collector runs; resources must be closed deterministically, because no guaranteed collection moment exists.
A leaked file handle keeps working until it does not: OS handles exhaust long before the heap has anything to collect. try-with-resources ties close() to scope exit; finalize tried to tie cleanup to collection and failed, which is why Cleaner exists.
try (var reader = Files.newBufferedReader(path)) { // closed deterministically on every path, exception or not }
Common misconception: That setting a reference to null is cleanup, or that the GC will close files eventually.
Follow-up: What made finalize unsafe to rely on?
How do you hunt a memory leak in Java?+
From a heap dump: find what still reaches the objects that should be gone. The retaining path names the culprit, usually a collection that only grows.
Dominator views rank objects by retained size; JFR and profilers show allocation pressure over time. The bug is almost never a GC tuning problem: it is an add without a remove, a static collection, or a ThreadLocal in a pooled thread.
Common misconception: That collector tuning fixes a leak. Settings change when memory is reclaimed, not whether it ever becomes reclaimable.
Follow-up: What would you check first in a web application that leaks per request?