override the finalize method
Hi guys
What happens if I override the finalize method present in the Object class and create a new instance of the object in the finalize method. Sample code given below. Will the GC will ever stop or will the JVM exit its a trick question I think that it is definitely a use case for the GC.
class MyClass{
public MyClass(){
//do some thing here
}
protectedvoid finalize(){
new MyClass();
}
}
[811 byte] By [
coolJacka] at [2007-11-27 6:47:58]

> What happens if I override the finalize method
> present in the Object class and create a new instance
> of the object in the finalize method. Sample code
> given below. Will the GC will ever stop or will the
> JVM exit its a trick question I think that it is
> definitely a use case for the GC.
1. The finalize() method is called just before the object in question is about to be collected ( deleted )
2. The finalize() method is not guaranteed to run; it may or it may not depending on whether the GC runs or not. So never put critical code in this method; in fact, you should avoid putting any code in this at all unless it's something like 4. below.
3. It is only called once; no matter what.
4. An object will on be garbage collected if there are no references to it; this means that, if in the finalize() method you assign this object to some reference, it will not be eligible for garbage collection anymore. But, from 3. above, you can only do this once! The next time, finalize() will NOT be called so you can do this trick again.
In this case, the one you mentioned,
>
> > class MyClass {
>
>public MyClass() {
>//do some thing here
>
>
>protected void finalize() {
>new MyClass();
>
> }
>
nothing will happen to this object. It will still be eligible for garbage collection ( it would have been, if finalize was called ). What will happen is that you've just created another object of this class with no references, an anonymous object. This will also be eligible for garbage collection and should soon be deleted, if the GC runs.
If you did want to preserve your object and avoid it being collected, you could have something like this:
protected void finalize()
{
someEarlierReferenceToMyClass = this;
}
[edit]
Also see these:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()
http://www.janeg.ca/scjp/gc/finalize.html
[/edit]
Message was edited by:
nogoodatcoding