Ch. 7 · Java

Java Garbage Collection and Retained Objects

Java Garbage Collection and Retained Objects. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readadvancedupdated Oct 3, 2026

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.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc