RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


How to Handle Java Finalization's Memory-Retention Issues : Page 4

Finalization allows you to perform postmortem cleanup on Java objects, but it can delay the reclamation of resources, even if you do not use it explicitly. Learn how to avoid such memory-retention problems.


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 native—and potentially scarce—resources 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-deterministic—and sometimes unpredictable—process. The less you rely on it, the smaller the impact it will have on the JVM and your application.

The author is grateful to Peter Kessler for his many constructive comments on this article.

Java is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.

Tony Printezis recently joined the development team of the Java HotSpot Virtual Machine at Sun Microsystems, after more than three years at SunLabs. He spends most of his time working on dynamic memory management, concentrating on the scalability, responsiveness, parallelism, and visualization of garbage collectors.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date