Forums Register Login

Garbage Collection

+Pie Number of slices to send: Send
Hi! Folks

Local variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. Each time the method comes into scope the local variables are re-created.

i've doubts:

1. In the above statement what does methods are eligible for garbage collection mean?


2. Does variables in method r candidates/eligible for gc??? yes, i know..once method exits variables go out of scope...but variables r not garbage collected.


i'm confused...


class A
{

String s;

A(String s) { this.s =s;}

public void finalize() { System.out.println(s);}

}


public class BDemo

{
double d;

public void static m1()
{

A a1 = new A("hello"); // 1

String s = new String("destroy"); //2


int j= 10; //3
String s = "s1"; //4
String s2 = "s2"; //5
String s2=s;

}

public static void main(String args[])
{

BDemo.m1(); System.gc();

}
}


In the above program when the method exits the variables 'n'objects created in the method go out of scope. Therefore "hello" 'n' "destroy" are eligible for gc as they r objects. What about j,s,s2 ??? R they candidates for gc.


Thank you in advance.
jaya
+Pie Number of slices to send: Send
First of all, a method is never garbage collected. You only GC objects and those are only GC'd when there is no longer a reference to them from an active part of the application.

So, let's say we have a local variable, like this:



When that method terminates, sb will be out of scope and the object referenced by sb will be eligible for garbage collection. What happens to sb? Well sb is just a reference variable - it just vanishes into thin air. It's gone...forever.

Same thing goes for pimitives. They're not objects so they're not garbage collected. Only objects are garbage collected.

I hope that helps.
+Pie Number of slices to send: Send
Hi! Corey

Thank you

jaya
Can you really tell me that we aren't dealing with suspicious baked goods? And then there is this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 536 times.
Similar Threads
objects eligible for GC?
Help with Garbage Collection
new object in method
GARBAGE COLLECTION (HFJ PG 266 )
few doubts
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 18, 2024 22:12:36.