aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in Garbage Collection........... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in Garbage Collection..........." Watch "Doubt in Garbage Collection..........." New topic
Author

Doubt in Garbage Collection...........

Manoj Mani
Ranch Hand

Joined: Mar 31, 2007
Posts: 65
class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}

public class GarbageCollection
{
public static void main(String[] args)
{
Animal a1 = new Cat();
Animal a2 = new Dog();
Animal a3 = a1;
a1 = null;
Animal a4 = a1;
Animal a5 = a2;
a1 = a2;
a2 = a4;
a5 = null;
a3 = a1;

// Here
}
}
When that code reaches the comment "Here" how many objects will be eligible for garbage collection?

This is the example taken from Corey's Blog.Only the cat object will be eligible for garbage collection..........? There are some other variables a4,a2,a5 which have null values in the last stage.Those variables will also be eligible for garbage collection,na?


Impossible Is Often Untried.Its Time For Us To Change....
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Manoj,

Good, you got the Corey's blog.


But unfortunately you missed the vital part of GC.
First of all, objects live on the heap and GC applies to only heap.
Reference variables live on the stack so there is nothing like GC on them.

You simply look at the "new" Operator. How many objects created using "new".
Yes exactly two. So we will work to find out how many reference variables still point to those two objects when you reach to the last line of the method.

You spotted well, only Cat object feels lonely because there is nobody to
reference it.

Finally:
"GC applies to objects not reference variable."

Regards,
cmbhatt


cmbhatt
Sasha Ruehmkorf
Ranch Hand

Joined: Mar 29, 2007
Posts: 115
Variables are never eligible for GC, only Objects!
And there have been created only two objects in your code: One Cat and one Dog-Object. As a2 and a5 still reference the Dog, only the Cat is eligible for GC
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
only one object which is Cat ,

draw the heap and you will get it
Manoj Mani
Ranch Hand

Joined: Mar 31, 2007
Posts: 65
Thanks three of you................I got it........
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Garbage Collection...........
 
Similar Threads
How many objects eligible for GC??
Garbage Collection
Another examLab casting question
Garbage Collector doubt (Examlab Diagnostic Test) Q4
question from Dan's exam - ClassCastException