tags:

views:

70

answers:

3

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?

+1  A: 

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.

andrewmu
+1  A: 

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.

Eyal Schneider
A: 

plus: if you forget to call super.finalize(), it could be a bug. so implementation of finalize() is error prone.

卢声远 Shengyuan Lu