Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between finally and finalize()

 
rajender polu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between finally block and finalize method? where finalize is useful?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34672
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajender,
Welcome to JavaRanch!

The finally block executes after a section of code in a method. For example, if you have code that might throw an exception, the finally block executes whether the exception is thrown or not. It is guaranteed to run.

The finalize method is supposed to be called before an object is garbage collected. It is not guaranteed to be called in that an object might not be garbage collected.
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When an object is to be garbage collected finalize() method will be called by the JVM only once. If we passed an reference to the object within finalize() (of course we should have override the finalize() within that class) then the object will not be garbage collected. But next time when the JVM decided to remove the object from the heap, finalize will not be called in that object since JVM knows it called the finalize once before in that same object.
[ September 07, 2008: Message edited by: Vijitha Kumara ]
 
arulk pillai
Author
Ranch Hand
Posts: 3387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as mentioned before you do not know when the objects are going to be finalized. Avoid using finalize() method to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these resources through the finalize() method. Finally is more useful.
 
James Basller
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by rajender polu:
what is the difference between finally block and finalize method? where finalize is useful?


finally block is used in Exception Handling.
When user wants his program to perform some action even though some exception occurs during program then he or she can write that code in finally block.
which is like,
try{
}catch(Exception e){
}finally{
//Code goes here
}


Where finalize() method is used for garbage collection when object is ready for garbage collection then Automatic Garbage collector will call finalize() method before destroying that object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic