GuruKulki
GuruKulki

Reputation: 26418

Garbage collector and finalize() method

You people may think that within 15-20 minutes i have asked 4-5 questions on the same topic, so I may need a tutorial on this. But i am getting these questions by reading about GC.

So my question is GC will call a finalize() method on an instance only once of its life cycle even though if the same object is made uneligible to garbage collect in its finalize() method. So i wanted to know that how GC will come to know that it has executed its finalize() method once before while collecting it for the second time

Upvotes: 1

Views: 474

Answers (3)

Steven Schlansker
Steven Schlansker

Reputation: 38526

Honestly, your life will be much better if you forget that finalizers exist. I've been coding Java for years and never had a reason to use a finalizer.

They're slow, not well defined (sometimes they'll never run!), and generally a PITA.

Do something along the lines of the Closeable interface instead if you are managing external resources, and use try{} finally{} blocks to clean up. Otherwise, try as much as you can to trust the language to clean up memory after itself.

Upvotes: 4

SyntaxT3rr0r
SyntaxT3rr0r

Reputation: 28293

Ah you again :)

Note that on the subject of finalizers, if you really FORCE a GC using JVMTI's ForceGargabeCollection, it is specifically stated that:

"This function does not cause finalizers to be run."

Once again, you probably do not really want to do that, but then if you have 2K+ rep and 5 questions about the GC is think that it's interesting to keep repeating that using JVMTI's ForceGarbageCollection you can really FORCE a GC.

Authoritative info as to how to force a GC:

http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html#ForceGarbageCollection

Upvotes: 0

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143094

Implementation dependent. Presumably the VM either has a secret bit on every object, or has a table containing objects that have already been "finalized". If I had to guess, I'd say the latter since presumably the set of already finalized objects that are still hanging around is expected to be small, so having a bit on every object in the system seems a bit wasteful.

Upvotes: 1

Related Questions