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¶
- Your code creates objects with
new. - They live on the heap.
- At some point, nothing references some of them anymore.
- 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:
onenow points to "Disney+", so "Netflix" loses its only reference. - Line 8: setting
onetonullremoves only one of three references. "Disney+" is still reachable. - Line 9: the method ends,
twoandthreego 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)