File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes finalize() and destroy() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finalize() and destroy()" Watch "finalize() and destroy()" New topic

finalize() and destroy()

Shashank Gokhale
Ranch Hand

Joined: Jan 07, 2003
Posts: 92
When and how is the finalize() method used in an application and the destroy method() used in an applet? Can you give me some coded examples?

May the force of the Java be in all of us !!!
J.H.B. Oosterlaar
Ranch Hand

Joined: Sep 12, 2002
Posts: 41
I don't know about the finalize() method, but the destroy() method is a standard method called by the garbage collector when the object is about to be destroyed.
You applet (or any other object) can override this method to do some cleaning up for example.
Shashank Gokhale
Ranch Hand

Joined: Jan 07, 2003
Posts: 92
Every tutorial book on java I have read says that the garbage collector is normally automatically called by Java as and when needed. So how would the explicit overriding of finalize() or destroy() help in disposing off objects? Besides, those books also say that Java does not let programmers call the garbage collection thread on demand; programmers can only mark objects for deletion by setting them to null or by removing all references to them. But again, why is it necessary to mark objects for deletion when garbage collection is an automatic process and is automatically done by the Java compiler when needed?
Please provide some code examples to clarify.
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
finalize and destroy are used to close system resources that may be allocated by the OS. Usually the browser handles the destroy() stuff unless you have something unusual to get rid of. finalize() may be used to close an IO stream or an HTTP or URL connection, etc. although this is usually handled before (like in the finally of an try/catch block). Use of finalize is discouraged in my experience.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I agree. Here's the link:
subject: finalize() and destroy()
jQuery in Action, 3rd edition