I was reading "Effective Java programming by Joshua Bloch. I this book he advices not to use the "finalize" block as its not guaranteed to be executed. Can anyone explain a bit more on this or give a link of some article which explains this in detail?
One problem with finalize is that it will not be called if your program calls System.exit()
- to deal with this I think Josh Block suggests that you use Runtime.addShutdownHook()
instead.
Another problem with finalizers, besides the one mentioned by andrewmu, is related to frequently created/destroyed objects.
When you define a finalizer for a class having a high creation/destruction rate, you add load to the finalizer thread, possibly slowing down the garbage collection rate of these objects. Instead of being released immediately when GC takes place, these objects wait in the finalizer thread queue to be finalized first. This increases the risk of an out of memory error.
plus: if you forget to call super.finalize(), it could be a bug. so implementation of finalize() is error prone.