Menu

How Java Garbage Collection Works: A Quick Walkthrough
📰

How Java Garbage Collection Works: A Quick Walkthrough

DEV Community: java·Vishnu B·7 days ago
#ARR7MZr9
#devtojava#devto#dev#collector#system
Reading 0:00
15s threshold

Java has no free() and no delete . You stop referencing an object, and at some point its memory quietly comes back. Someone is doing that work: the garbage collector. Let's pin down the rule it uses, watch a real JVM collect live, and then be honest about where the JVM ends and the operating system begins.

The one rule: reachability

The collector does not count references or guess. It starts from a fixed set of entry points called GC roots - local variables on every live thread's stack, static fields, and a few JVM internals - and walks the object graph from there. Anything it can reach stays. Everything else is garbage, even if two unreachable objects still point at each other.

That animation is the classic mark-and-sweep idea, and it is a mental model, not a literal description of any one collector: mark everything reachable from the roots, sweep away the rest.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.