Can someone tell me more about the finalize method? For example, when is it invoked? Is it invoked by the garbage collecter implicitly or does the programmer have to do it herself? If I call the garbage collector for a subclass, do I have to call it for the superclass as well? Can I force garbage collection using "getRuntime.gc();"? Thanks for your help.
The finalize method is called before the object is Garbage collected. No, you don't call the finalizer method yourself. Also, you can not force GC, you can suggest to the VM the GC be run, but there is no guarantee as to when/if it will actually happen. Note that if an objecet is not GC'ed, it's finalize method (if there is one) will not be executed either.
Bosun (SCJP, SCWCD).
So much trouble in the world -- Bob Marley
finalize() on an object will be called just before an object is garbage collected. If you want to do some specific thing before a particular obejct is garbage collected, you write it in the finalize() method for that object.
The finalize() method is called automatically by Java before an object is finally destroyed and the space it occupies in memory is released. This method is useful if your class objects use resources that require some special action when they are destroyed. Another use for the finalize()method is to record the fact that the object has been destroyed. Coutersy:Ivor Horton's book Beginning Java 2
Thank you Boson, Sunetra and Sarah for all of your replies. I'm a lot clearer now. To summarize: 1. The garbage collector can be invoked explicitly using a Runtime object, but it cannot be forced to run. Only the JVM is able to do that. 2. The finalize() is called by the JVM before an object is destroyed by the garbage collector. This method should be overridden is the programmer feels that there are certain codes to be executed (i.e if the object uses certain system resources) before the object is garbage collected. 3. The finalize() is only invoked when the object is about to be garbage collected. 4. Any class that includes a finalize method should invoke its superclass' finalize method. I'm not very sure about point 4. Can someone verify it for me?
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop