简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM