Search code examples
javagarbage-collection

Is this Java Magazine Quiz answer is correct on Java Garbage Collector


As per my understanding of the below code snippet, the Car object will become eligible for GC after line no. 12. But the given solution says it will not. Can anyone check the below link and correct me if I am wrong?

01: var rl = new ArrayList<Repairable>();
02: var car = new Car();
03: var clutch = car.getClutch();
04: var engine = (Repairable) null;
05: rl.add(car);
06: rl.add(clutch);
07: car = null;
08: clutch = null;
09: rl.add(engine);
10: rl.set(2, engine);
11: rl.remove(0);
12: rl.remove(1);

https://blogs.oracle.com/javamagazine/post/java-quiz-object-reachability

Update: The article says "Car object will not become eligible for GC even after line 12."

I am not agreeing especially on this line. At index 1, the value is not null it actually holds the clutch object

Line 12 removes the item at index 1, which is the null. The list, therefore, contains nothing except the clutch.


Solution

  • You have missed that the first call to remove shifts the indexes of the other elements. remove(1) on line 12 removes the null; clutch is still in the array, and clutch contains a reference to the Car because it is nonstatic.