1

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?

bzlm
  • 9,626
  • 6
  • 65
  • 92
Vishal
  • 2,711
  • 7
  • 33
  • 42
  • 2
    Why were you planning on using finalizers? I think the most common problem with finalizers in Java is that people think they act the same as destructors in C++. :) (Also, your wording "finalize block" risks confusion with "finally blocks". Finalizers are not blocks per se.) – bzlm Aug 05 '10 at 10:27
  • Are you shure they mean finalize blocks, and not finalize methods? – Marcus Johansson Aug 05 '10 at 10:28
  • These aren't dupes but very closely related http://stackoverflow.com/questions/2954948/performance-implications-of-finalizers-on-jvm/2955757#2955757 (many quotes from the item from the book) ; http://stackoverflow.com/questions/3038211/what-happens-if-an-exception-is-thrown-during-finalize ; http://stackoverflow.com/questions/2860121/why-do-finalizers-have-a-severe-performance-penalty – polygenelubricants Aug 05 '10 at 10:28
  • No. I am not planning to use them. I just want to know why its not advised to use them? Why they are forbidden - like 'goto' statements in C ? – Vishal Aug 05 '10 at 10:29
  • 4
    If you were reading Effective Java, then its has quite a detail information about finalize method. Read Item 6 – naikus Aug 05 '10 at 10:30
  • @bzlm Thanks for correcting that. :) @naikus Yea that books gives a details explanation. But I don't have that book with me right now. :( I just read a bit of that topic before a friend borrowed it. – Vishal Aug 05 '10 at 10:36

3 Answers3

1

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
  • 14,276
  • 4
  • 39
  • 37
1

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
  • 22,166
  • 5
  • 47
  • 78
0

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

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130