It's not a secret anymore!
The moose likes Beginning Java and the fly likes finalize Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finalize " Watch "finalize " New topic


Glenny Dsilva
Ranch Hand

Joined: May 09, 2005
Posts: 42
I have used finally block for closing connections etc.

But i do not know when is finalize used.

can i get an example.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

The answer for most developers is "almost never". Finalize is (in theory) called before an object is garbage collected, or if you make a call to System.runFinalization() (it should be noted however that neither method guarentees all finailers will be run). However since there is no guarentee when (or even if) an object is garbage collected finalize is not a good candidate for the same sort of clean up operations you might perform in a finally block. I can't think of a good reason to use finalize, other than perhaps to observe how the GC is disposing of objects.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
And remember the classic case where the finalisation prevents the object from being destructed (by creating new references to it).
In that case the finaliser will NOT be called the next time the object enters the garbage collection system so such safeguards work at most once for each object.

I agree. Here's the link:
subject: finalize
It's not a secret anymore!