• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

finalize() and destroy()

 
Shashank Gokhale
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
J.H.B. Oosterlaar
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic