This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Manoj Mani
Ranch Hand
Posts: 65
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sasha Ruehmkorf
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 98
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
only one object which is Cat ,

draw the heap and you will get it
 
Manoj Mani
Ranch Hand
Posts: 65
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks three of you................I got it........
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic