Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Do we need to call finalize() method explicitly on an object?  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
Is it necessary to call finalize() method on an abject explicitly or it will be called by garbage Collector automatically whenever the object eligible for Garbage Collection..?

Please answer this.
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any search to google will tell you that its called implicitly by the GC when it determines that the object cannot be reached. I believe putting anything much in it is discouraged, even to the point of never using it.
 
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Tom said, it is called automatically by the GC. But you can still call it explicitly but that is discouraged and that will not destroy the object from the heap. Also the finalize method has been declared protected in the Object class so that you can make it inaccessible from outside your class and its sub classes. This is done solely to restrict any code outside your class (and its sub classes) from calling the finalize method...
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess we can override the defualt finalize() method !!! .......... may be sometimes useful..to make the members null referenced !!
 
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to read this : Effective Java: Item 6 Avoid Finalizers
 
Sandeep Kumar Jakkaraju
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ... I didn't load this book onto my classpath yet ..... so just thought finalize might me useful .....
 
Sheriff
Posts: 21256
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Sandeep Kumar Jakkaraju wrote:I guess we can override the defualt finalize() method !!! .......... may be sometimes useful..to make the members null referenced !!


If you do, always call super.finalize():

I usually only add finalizers to make sure that resources are released, but I always provide means to release resources explicitly. Like Monu's link says, finalizers should only be used as a safety net of sorts; never rely on it, only use it "just in case".
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!