To Finalize Or Not To Finalize
By templedf on Sep 07, 2006
Because of some API work I'm currently doing, I was recently faced with the question of whether or not to use a finalizer to simplify the API. Searching on the Internet turns up lots of articles (mostly from IBM) saying that finalizers are bad and should be avoided. Since I work for Sun, I thought it would be a good idea to find out what our official stance is. This post is a summary of the answers I got.
First off, a little background reading. These articles were recommended to me by Sun engineering:
- How to Handle Java Finalization's Memory-Retention Issues -- Tony Printezis
- Java theory and practice: Garbage collection and performance -- Brian Goetz
In addition, I found the following articles helpful:
- Finalization, threads, and the Java technology-based memory model -- Hans-J. Boehm
- Gems from e-BIT: Why finalizers should (and can) be avoided -- Phil Vickers
From those articles and from direct feedback from various Sun engineers, these are the lessons about finalizers that I have gathered:
- If there's a way around using a finalizer, and it's not ridiculously more complicated, do it. See Tony Printezis' article for some alternatives to finalizers. In many cases, an explicit dispose() method is the best choice.
- Never trust a finalizer to free something that has no other way of being freed. There is no guarantee that a finalizer will ever run. For example, deleting lock files is something that definitely should not happen in a finalizer, unless it also happens somewhere else.
- If you're designing an API that may have a JNI-based implementation, either design in explicit dispose() methods, or make sure there's a common clean-up point where held resources can be freed, such as exiting the session, so that implementers are not forced to use finalizers.
- The Java language's specification of finalizers has some holes which allow you to do bad things (such as restoring a reference to the object being finalized). If forced to use a finalizer, do so carefully.
In my end, my findings were exactly what my initial searches suggested. It is, however, nice to have confirmation.