File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to ensure finalize() is called?

 
Christopher Paul
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 245
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 232
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Christopher Paul
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Naveen Vooka
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic