Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finalize() and destroy()" Watch "finalize() and destroy()" New topic
Author

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
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
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.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: finalize() and destroy()