Skip to content

The garbage collector, and tracing eligibility

โ˜• Java 17 ยท Destroying Objects and Memory Management ยท 2/2

An object with no reachable reference is eligible for collection. Here's what happens next, and how to spot that moment in code.

What the collector does

  1. Your code creates objects with new.
  2. They live on the heap.
  3. At some point, nothing references some of them anymore.
  4. The garbage collector finds those unreachable objects and reclaims their memory.

Four facts to keep in mind:

Fact Meaning
Automatic no delete, no free(): Java cleans up for you
Unpredictable timing the JVM decides when to collect, based on memory needs
System.gc() is only a hint it suggests a collection; the JVM may ignore it
No guarantee at all a program can end without the collector ever running

So "eligible for garbage collection" and "deleted" are two different things. Code can only control the first.

Tracing eligibility, line by line

To find when an object becomes eligible, count its references after each line:

1:  public class StreamingPlatform {
2:      public static void main(String[] args) {
3:          String one, two;
4:          one = new String("Netflix");
5:          two = new String("Disney+");
6:          one = two;
7:          String three = one;
8:          one = null;
9:      }
10: }
After line "Netflix" referenced by "Disney+" referenced by
5 one two
6 nobody โ†’ eligible one, two
7 โ€” one, two, three
8 โ€” two, three
9 โ€” nobody (method ended) โ†’ eligible
  • Line 6: one now points to "Disney+", so "Netflix" loses its only reference.
  • Line 8: setting one to null removes only one of three references. "Disney+" is still reachable.
  • Line 9: the method ends, two and three go out of scope, and "Disney+" becomes eligible.

The method: draw each object, draw an arrow for each reference, and update the arrows line by line. An object with no arrow left is eligible.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

โ† Unreachable objects ยท Back to the series


๐ŸŽ“ Preparing the OCP Java 17 exam? Exam traps and practice questions for this section โ†’ (optional)