Stevens Miller wrote:
yaswanth yash wrote:public class Test {
Test t1 = new Test(); // line 1
public static void main(String[] ar) {
new Test(); // line 2
Test t2 = new Test(); // line 3
}
}
hi stevens,
can you tell me,
After how much time the objects created at lines 1,2,3 in this program
are made eligible for garbage collection??
Good Gracious, yaswanth, what are you trying to do here??? As Paul said, no object created by this code will ever be eligible since none of them ever lacks a reference, because that "new Test()" call results in an infinite sequence of Test objects creating more Test objects. (To be a bit of a nit-picker about it, I wouldn't say it "goes into a loop," but that it results in infinite recursion, which Paul clearly knew when he warned that the program will crash with a stack overflow.)
And do you mean to say that making an object eligible for garbage collection means dereferencing that object ?!
If I understand your question, the answer is "yes." When there are no outstanding references to an object, it is eligible for garbage collection.
Paul's right. Learning about the GC can wait. Mostly, the only thing to learn about it is that there really isn't anything to learn about it. As a new Java programmer, I found myself very concerned about it, thinking that maybe I needed to call it explicitly here and there, to be sure my program wasn't using up memory for no reason. Well, it turns out that the people who wrote the GC knew what they were doing. The GC will always be called if your application tries to get more memory than it can, so don't worry that you will ever run out of resources for lack of calling it yourself. I'm no GC expert, but I believe it also tries to hold off running while your application isn't blocked. That is, it runs when it really should run, and not when it really shouldn't. And, like I said before, you simply cannot force it to run; best you can do is ask it to run. Hard as it may seem, the bad news is that you just have to trust it. The good news is that it is worthy of your trust.