Build a practical mental model of object allocation, references, and garbage collection.

The core idea

Local variables and call frames are commonly associated with a thread’s stack, while objects are generally allocated on the heap. The garbage collector reclaims objects that are no longer reachable; it does not guarantee immediate cleanup at a particular line.

A practical way to approach it

Follow references from static fields, active stack frames, and other reachable objects to understand why an object remains alive. Use profilers and heap dumps to investigate memory growth instead of guessing from source code alone.

Try it in a small project

Create a small program that retains objects in a static collection, observe memory growth, then remove the references and compare behavior. Treat this as a learning experiment, not a production memory test.

Common mistakes to avoid

Avoid relying on finalization for resource cleanup. Close files, sockets, and database connections explicitly with try-with-resources or framework-managed lifecycles.

Key takeaway

Keep the first version small, make your assumptions explicit, and verify the result with a repeatable test. For production use, check the current official documentation for the tools and versions you choose.