Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Garbage Collection  RSS feed

 
Henry Zhi Lin
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got the following from exam lab,



How many object can be garbage collected here?

My answer is 0, but the correct answer is 1.

I am so confused here and find there is no alternative way to solve problem like this. Can anyone tip me how to solve such gc problem?

Thanks.
 
Henry Wong
author
Sheriff
Posts: 23275
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's name the object OA, OB, OC, OD, etc., as they are being created. This is to distinguish them from the reference that points to it. Furthermore, we will follow the instance variable that is part of these objects, to draw all the connections.

---------------------
After...

A a1=null;
A a2=new A(new A(null));
A a3=new A(a2);

You will get...



---------------------
After ...

a1=a3;

You will get...



---------------------
After ...

a1.a=new A(null);

You will get...



----------------------
After ...
a2.a=null;

You will get ...


And as you can see, the B object is now unreachable.

Henry
 
Henry Zhi Lin
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry,

You method are really cool. It is very clear what really happens.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!