This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to ensure finalize() is called? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to ensure finalize() is called?" Watch "How to ensure finalize() is called?" New topic
Author

How to ensure finalize() is called?

Christopher Paul
Greenhorn

Joined: Oct 05, 2005
Posts: 4
I want finalize() in my class called, but I don't know how to ensure that it is called, and I read I'm not supposed to call it myself.
Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
finalize() is designed to be called automatically before garbage collecting the object. And garbage collection can't be forced so finalization can't be forced.

If you need to close some resources (files, connections, ...), create a normal method which does it (instead of finalize). Then call it when finished working with the resource(s) (use try-(catch)-finally to ensure that it gets called).
Sripathi Krishnamurthy
Ranch Hand

Joined: Mar 07, 2005
Posts: 232
Originally posted by Christopher Paul:
I want finalize() in my class called, but I don't know how to ensure that it is called, and I read I'm not supposed to call it myself.


use Syste.gc(). This will garbage collect the not required instances.
you can also use System.runFinalization();
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Sripathi Krishnamurthy:

use Syste.gc(). This will garbage collect the not required instances.
you can also use System.runFinalization();


No, actually. Neither of these methods is guaranteed to do anything. They are both merely suggestions to the JVM, and as such, can be ignored. Don't bother with them.

Vlado Zajac's suggestion is the conventional and correct answer. finalize() simply isn't terribly useful because of the nondeterminate nature of garbage collection.


[Jess in Action][AskingGoodQuestions]
Christopher Paul
Greenhorn

Joined: Oct 05, 2005
Posts: 4
Thanks!
Naveen Vooka
Greenhorn

Joined: Oct 13, 2004
Posts: 25
useful links
http://www.codeguru.com/java/tij/tij0051.shtml
http://www.firstsql.com/java/gotchas/

--------------
Naveen Vooka
www.devsquare.com
DevSquare - Online Application Development
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to ensure finalize() is called?