Java GC and parameter passing: When is the Demo object created in start() eligible for garbage collection? class Test { private Demo d; void start() { d = new Demo(); this.takeDemo(d); // line 7 } // line 8 void takeDemo(Demo demo) { demo = null; demo = new Demo(); } }

Difficulty: Medium

Correct Answer: When the instance of Test running this code becomes eligible for GC

Explanation:


Introduction / Context:
This problem examines the relationship between instance fields, method parameters, and object reachability. Despite assigning demo = null inside the callee, the field d in the caller still references the original Demo.



Given Data / Assumptions:

  • d is an instance field of Test.
  • start() assigns d = new Demo() and then passes it to takeDemo.
  • takeDemo sets its parameter reference to null and later to a new Demo, but does not modify this.d.


Concept / Approach:
Method parameters are local variables; setting demo to null does not affect the caller's field. The original Demo object remains referenced by this.d. That Demo becomes eligible only when no live references point to it—typically when the owning Test instance itself becomes unreachable or its field is reassigned to another object or null.



Step-by-Step Reasoning:

start(): create Demo and store in field d.takeDemo: parameter demo manipulations do not change d.After returning, d still references the original Demo.Therefore, eligibility occurs when the Test instance (and thus d) becomes unreachable or d is overwritten.


Verification / Alternative check:
Log System.identityHashCode(d) before and after takeDemo; it stays the same.



Why Other Options Are Wrong:
Lines 7/8 or method completion do not drop the only reference; parameter nulling is irrelevant to the field. Only losing the field reference (or object graph containing it) makes the Demo collectible.



Common Pitfalls:
Assuming pass-by-reference; forgetting that parameters are copies of references.



Final Answer:
When the instance of Test running this code becomes eligible for GC

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion