File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic

Garbage Collection

Henry Zhi Lin
Ranch Hand

Joined: Nov 04, 2008
Posts: 69
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?


SCJP 5.0
Henry Wong

Joined: Sep 28, 2004
Posts: 20380

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.


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

You will get...

After ...


You will get...

After ...

a1.a=new A(null);

You will get...

After ...

You will get ...

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Henry Zhi Lin
Ranch Hand

Joined: Nov 04, 2008
Posts: 69
Thanks Henry,

You method are really cool. It is very clear what really happens.
It is sorta covered in the JavaRanch Style Guide.
subject: Garbage Collection
It's not a secret anymore!