Advanced 12 min

References, garbage collection, and leaks

Java can reclaim an object when it is no longer reachable from the running program.

How it works

Trace arrows from objects that are still useful to the running program. If any arrow chain reaches a cached object, that object cannot be reclaimed. When investigating growth, ask which long-lived collection or listener still holds the reference.

Walk through an example

Removing the final reachable reference to an object makes it eligible for collection. A long-lived map that still points to the object keeps it reachable.

What to watch for

Eligibility does not imply immediate collection. Bound caches and release listeners when their owner is finished with them.

Check your understanding

Can the object be collected while the reachable map keeps it?

See the example and explanation
Worked example
Given A cache map still holds an object after the local variable is cleared.
Answer No.

The cache still provides a path to the object, so the object remains reachable.

Open practice problem
Next lessonUnderstanding JVM performance