Garbage collection reclaims unreachable objects. Long-lived references can retain unused data even when no explicit allocation loop looks suspicious.
Before you start
You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.
The practical goal is to reason through this situation: A static cache holds every request result indefinitely. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Measure live data
Inspect memory remaining after collection rather than allocation spikes alone.
Step 2: Follow retaining paths
Find why unused data remains reachable from long-lived owners.
Step 3: Bound ownership
Apply capacity and expiry policies to caches and remove obsolete listeners or references.
Worked scenario
A static cache holds every request result indefinitely.
A static map stores every request result forever. Those objects are reachable, so garbage collection correctly retains them. Increasing heap only delays exhaustion. A bounded cache changes ownership duration, but its eviction and hit-rate tradeoffs must match the application’s requirements.
Common mistake
Increasing heap size can delay symptoms without correcting retention.
Verify the behavior
Compare post-collection live heap across repeated workloads and verify the cache reaches a stable bound.
Interview exercise
Investigate rising live heap.
Answer and reasoning
Compare post-collection live data, inspect retaining paths and add a bounded cache policy when ownership exceeds intended lifetime.
Continue learning
Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.