CoursesJVM internals for Kotlin and Android developers
Puzzle 3 · 4 of 5
When can a counter be reclaimed?
Trace which object the remaining variable can reach.
All puzzles in this course
The problem
The caller clears the second name and then reads the first. Did the object disappear when one name was cleared?
See it
Scroll sideways to see the full diagram.
Both caller variables reach the same counter.
Step 1 of 4The second reference is cleared.
Step 2 of 4The first reference still allows a read.
Step 3 of 4One remaining path is enough here.
Step 4 of 4
The building block
Draw locals first and objects second. After edit returns, first and second still point to the original counter. Clearing second removes one arrow. The subsequent read through first still reaches eight. The temporary counter created inside edit has no surviving reference in this example. The runtime may reclaim its storage. The printed values cannot establish when collection ran, or whether an optimizing runtime materialized that temporary allocation at all. This distinction matters when investigating a long-lived cache that still points to old objects.
The garbage collector manages storage for objects. To reason about ordinary, strongly held references, start with values that the running program can still use. A root is one of these starting points in your drawing. Follow their references and mark every object reached. A cache is a collection that keeps values for later reuse. If a live application keeps a cache, references stored in its entries also matter.
| Change to the example | Objects still reachable | Path that proves it |
|---|---|---|
| A live local and the cache both hold A. A holds B. Clear the local. | A and B | cache to A to B |
| Also remove A's link to B. | A only | cache to A |
| Instead, start again and clear both the local and the cache entry. | Neither A nor B | no path from a root |
The rows assume there are no other references. Add a link from B back to A in the last row. The two objects now point at each other. A traversal starting from the roots still reaches neither. Conversely, retaining a single cache entry can keep a large group of objects alive. To diagnose unexpected retention, look for a path from a live owner to that group. The number of times a method returned tells you little about this path.
Try it
Optional local lab
Complete experiment 4 in the JVM source files. Record your prediction before running the program.
Check yourself
Sources
- Java language specification, reachability — “can be accessed in any potential continuing computation from any live thread”
What you now know
Losing one reference leaves the object reachable while another live reference still leads to it.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.