• Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding finalize and finally apart from resource release  RSS feed

 
Lathishbabu Ganesan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having very basic doubt related to resource releasing.

Below is my understanding,

finally block is used to release the resource like connection,file etc once the try,catch block is executed.

finalize method is used to release the resource just before the object is eligible for GC.

What is potential benefit of having two components which is doing similar job? I'm not expecting Javaspec, looking for deeper understanding of the two functionalities.

Thank you for your time
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
finally and finalize() methods are really two different things, and they don't have a similar purpose.

A finally block is called at the end of a try block, and the crucial thing is that it is always called, whether an exception happened or not. Its purpose is to cleanup resources that have been used in the method that contains the try block, even in case an exception happened.

A finalize() method is called when the garbage collector is about to destroy an object. Note that it is unpredictable when this is called, and there is even no guarantee that a finalize() method will ever be called - in fact, if you stop a Java process then the JVM just stops immediately, and it will not call finalize() on all objects that are in memory at that moment. In practice, finalize() methods are almost never used, because they are not very useful.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

About the only instance where finalize() might be useful is if the object uses non‑Java resources which haven't been released. Even then it should be unnecessary because the resources should already have been released.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only time I can think of that I ever wrote a finalize() method was so that I could log when an object was being garbage collected without its 'close' method being called, which in the case of my class may have resulted in a resource leak.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!