Rollerball
Rollerball

Reputation: 13108

Garbage Collection's working

Here I have a Java doubt regarding the Garbage Collection:

protected class Robocop {
Integer weight = 200;

Robocop attent(Robocop rb) {
rb = null;
return rb;
}
public static void main(String[] args) {
System.out.println("indeed the solution is behind the corner);

Robocop rb1 = new Robocop();

Robocop rb2 = new Robocop();

Robocop rb3 = rb1.attent(rb2);

rb1 = null;

}
}

How many objects do you reckon are going to be eligible for GC?

My take on this, would be 4 object to be garbage collected rb3, rb1 and the related Integer wrapper instance variables.

Upvotes: 0

Views: 70

Answers (2)

Amir Kost
Amir Kost

Reputation: 2168

It's probably best to try it with a profiler, which can show the exact number of objects at any given time. It looks like you have a typo in your code. You probably meant Robocop rb3 = rb1.attent(r2); Assuming that this is what you meant, rb2 will be eligible for GC, and then rb1 will be eligible as well, since they point to null.
So the answer is 2.

Upvotes: 0

Andrew Logvinov
Andrew Logvinov

Reputation: 21831

Inside your method you could as well just return null since you get a copy of reference as argument to your method, not the original reference itself. Thus, you cannot modify original reference inside of your method. You can only modify the object this reference refers to.

Right at the end of main, 2 objects will be eligible for GC: one Robocop (with one Integer inside).

After main has finished, JVM will just shut down (in your case) and no GC will happen.

Upvotes: 2

Related Questions