Re: Garbage collector and references
Mohammad Javad Dousti wrote:
Hi,
Please assume this little program:
class A{
int m;
}
class B{
public static void main(String[] args)
{
new A();
//do some other works
}}
So, does garbage collector delete A after newing it?
Good question, because understanding garbage collection (GC) is important.
Optimization has an effect here, too.
The only generally accurate answer is, "It depends."
It is possible the optimizer might not even let the JVM instantiate an A,
which I'm going to call Foo because that is easier to read than a
single-letter class name.
In the event that the JVM does create an instance of Foo, there is no
requirement that GC ever reclaim its storage. That little bit of heap might
remain there for the rest of the application.
Or not.
Under certain circumstances it is conceivable that rather than GCing the
memory formerly occupied by an object, the optimizer will make the JVM reuse
it for a newly-created instance. For example:
for( int i = 0; i < LEN; ++i )
{
Foo foo = new Foo();
doSomething( foo );
}
Although each time around the loop 'foo' points to a new instance, not in any
way related to the last time(s) through the loop, the optimizer *might* decide
to re-use the storage for each new instance, thus saving a couple of clock
cycles for instantiation. GC would not be relevant in that situation until
after the loop finishes. (Assuming no finalize() override.)
If this does not happen, then old Foo instances will probably hang around for
a while. If the "young" generation fills up, the GC will want to get rid of
the storage used by those old instances, and will reclaim some or all of that
storage. Or it might not need to, and the storage will remain unclaimed until
the program terminates.
Objects with a short lifetime, like our 'foo' inside a tight loop, will tend
to get cleaned up more quickly.
In a meaningful way the object is "deleted" right at the moment that nothing
inside the program refers to it any more, directly or indirectly. That is
really all the "deleted" you need. "Garbage collected" is a different issue,
involving running finalizers and reclaiming memory, and no guarantees that
it'll even happen for any given object.
--
Lew