Use Finalization Only When You Must
This article briefly described how finalization is implemented in a JVM. It then gave examples of how memory can be unnecessarily retained by finalizable objects and outlined solutions to such problems. Finally, it described a method that uses weak references instead of finalization, which allows you to perform postmortem cleanup in a more flexible and predictable manner.
However, total reliance on the garbage collector to identify unreachable objects so that their associated nativeand potentially scarceresources can be reclaimed has a serious flaw: memory is typically plentiful, and guarding a potentially scarce resource with a plentiful one is not a good strategy. So, when you use an object that you know has native resources associated with it (e.g., a GUI component, file, socket), by all means call its dispose() or equivalent method when you are done with it. This will ensure the immediate reclamation of the native resources and decrease the probability of those resources running out. This way, you will use the approaches discussed in this article for postmortem cleanup only as last resorts and not as main cleanup mechanisms.
You should also try to limit your use of finalization to only when it is absolutely necessary. Finalization is a non-deterministicand sometimes unpredictableprocess. The less you rely on it, the smaller the impact it will have on the JVM and your application.
Acknowledgments
The author is grateful to Peter Kessler for his many constructive comments on this article.
Trademarks
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.