What is a WeakReference in Java, and when is its referent reclaimed by the garbage collector?
answer
- Wrapper that doesn't keep its referent alive
- Cleared at next GC once only weakly reachable
- get() returns null after reclamation
- Weak = eager; Soft = under memory pressure
- WeakHashMap holds keys weakly
basics
~20 sA WeakReference holds an object without keeping it alive. Once nothing else strongly points to that object, the garbage collector can reclaim it at the next collection, and the weak reference's get() then returns null.
solid answer
~50 sA WeakReference<T> is a wrapper from java.lang.ref that references an object (the 'referent') without contributing to its reachability. The collector treats weak references as not counting toward keeping an object alive: as soon as the referent is only weakly reachable (no strong or soft references reach it), the GC is free to reclaim it at the next collection cycle, regardless of how much memory is available. After reclamation, calling get() returns null. You use weak references to associate data with an object without preventing that object from being collected — for example caches or metadata side-tables keyed by identity. Contrast with strong references (the default, never collected while reachable) and soft references (cleared only under memory pressure). You typically null-check the result of get() before using it, since the referent can disappear at any time.
go deeper
Knows a WeakReference points at an object without keeping it alive, and that get() returns null once the object is gone.
Can place weak on the reachability ladder (strong/soft/weak/phantom), explain 'weakly reachable', and contrast weak (eager) vs soft (memory-pressure) clearing; names WeakHashMap as the canonical use.
Explains the reachability model precisely, the null-check discipline around get(), why weak suits identity-keyed side-tables, and the failure modes (value strongly referencing its key).
Reasons about when weak references are the right design vs alternatives (explicit eviction, bounded caches), GC-pause and liveness implications, and ties the choice to system-wide memory-management strategy.
## The problem weak references solve In Java you don't free memory yourself — the **garbage collector (GC)** does. The GC reclaims any object that is no longer **reachable**: that is, that can no longer be reached by following a chain of references starting from a **GC root** (things like local variables on a running thread's stack, static fields, and active threads). An ordinary variable — `Customer c = new Customer();` — is a **strong reference**. As long as a strong reference chain reaches an object, the GC will never collect it. Sometimes that is exactly what you do NOT want. Suppose you want to attach extra data to an object (say, cache a computed value for it) but you do **not** want your bookkeeping to keep that object alive forever. If you store it in an ordinary (strong) map, the map's strong reference pins the object in memory for as long as the map lives — even after the rest of the program is done with it. That is an unintended memory leak. ## What a WeakReference is `java.lang.ref.WeakReference<T>` is a small wrapper object. The thing it points to is called the **referent**. The key property: a weak reference does **not** count as a reference for reachability purposes. The GC defines a referent as **weakly reachable** when the only references that reach it are weak ones (no strong and no soft reference). When the GC discovers an object is merely weakly reachable, it is allowed to reclaim it **at the next garbage collection** — immediately, without waiting for memory pressure. ```java Object obj = new Object(); // strong reference WeakReference<Object> weak = new WeakReference<>(obj); System.out.println(weak.get()); // prints the object — still strongly reachable via obj obj = null; // drop the only strong reference System.gc(); // suggest a collection System.out.println(weak.get()); // likely prints null — referent was reclaimed ``` After the referent is reclaimed, `weak.get()` returns `null`. Before that, `get()` returns the referent (and momentarily creates a strong reference to it on your stack, so it is safe to use once you've fetched a non-null value). ## The reachability ladder Java has a graded set of reference strengths, from strongest to weakest: - **Strong** — the default. Never collected while reachable. - **Soft** (`SoftReference`) — cleared by the GC **only when the JVM is running low on memory**, just before it would throw `OutOfMemoryError`. Good for memory-sensitive caches. - **Weak** (`WeakReference`) — cleared **eagerly** at the next GC once only weakly reachable, regardless of memory. - **Phantom** (`PhantomReference`) — used only for post-mortem cleanup notification; `get()` always returns null. The practical contrast for interviews: **soft = keep until memory is tight; weak = drop as soon as nobody else needs it.** ## The canonical use: WeakHashMap The most common place weak references appear is `java.util.WeakHashMap`. It is a `Map` whose **keys** are held by weak references. When a key object becomes otherwise-unreachable (nothing else in the program strongly references it), the corresponding entry is automatically removed from the map. This makes it ideal as a **metadata side-table** or a **canonicalizing map**: you can associate data with objects you don't own, and the entries disappear by themselves when those objects are no longer in use, so the map can't leak them. (Note: it's the *keys* that are weak, not the values — and a value that strongly references its own key defeats the mechanism.) ## Caveats - The result of `get()` can become `null` at any time; always null-check before use. - A weak referent can be reclaimed even if it still has weak references pointing at it — weakness doesn't keep anything alive. - Weak references don't *cause* collection; they merely fail to *prevent* it. The actual timing is up to the GC.
- How does a weak reference differ from a soft reference?Both don't strongly keep the object alive, but a weak referent is cleared eagerly at the next GC once it is only weakly reachable, while a soft referent is retained as long as possible and cleared only when the JVM is under memory pressure (just before OutOfMemoryError). Soft suits memory-sensitive caches; weak suits drop-as-soon-as-unused metadata.
- If I hold a WeakReference to an object, can it still be collected?Yes. A weak reference never prevents collection. As soon as no strong (or soft) reference reaches the object, the GC may reclaim it at the next collection, and the weak reference's get() will return null.
saying these in an interview costs you the question
- Saying a weak reference keeps the object alive — it does the opposite
- Claiming weak references are cleared only under memory pressure (that's soft references)
- Forgetting that get() can return null and dereferencing it
- Thinking GC timing is guaranteed/immediate rather than 'at the next collection'