Return to site

☕🎓JAVA CERTIFICATION QUESTION: enclosing instance reference reachable when nested class is reachable

· java,ocp

Given the following code:

and a method fragment:

After which line will the Car instance created at line 02 become eligible for garbage collection? Choose one.

* It will become eligible after line 07.

* It will become eligible after line 08.

* It will become eligible after line 10.

* It will become eligible after line 11.

* It will become eligible after line 12.

* It will not become eligible after line 12.

#java #certificationquestion #ocp

Answer:It will not become eligible after line 12.

There are a single thread and four variables: r1, car, clutch, and engine.

From those variables, you should consider the transitive reachability.

That is, if you have added car to the list, you can get at car through the reference rl, because you can follow rl to the list and then from the list you can access car.

By the end of line 06, the variable rl refers to the ArrayList, and that list contains references to both the Car and the Clutch objects.

At that same point, the car variable also refers to the Car object.

Clearly the Car object is reachable at this point.

By the end of line 10, the car and clutch variables have been nulled out

—but the list still contains references to both the Car and Clutch objects, so the Car object is still reachable.

Line 09 appends engine (which contains null) to the list, placing null at index 2.

Line 10 has no meaningful effect on the state of things.

Line 11 removes the item at index 0, which is the car.

Continuing to trace the execution, at this point the list now contains the clutch and null.

Line 12 removes the item at index 1, which is the null.

The list, therefore, contains nothing except the clutch.

What’s not immediately obvious is that the Clutch object itself, which is an inner class, contains a reference to its enclosing instance, which is the Car object.

Because of that reference, the Car object is still reachable after line 12, so Car instance will not become eligible after line 12.