By olaf.heimburger on September 18, 2007 9:11 AM
Memory Leaks? We have a Garbage Collector!
True. Java comes with a Garbage Collector and makes reclaiming of heap space easier. On the other hand, Java offers a number of features, which, if used carelessly, can be the root for your memory leak nightmares.
Simple and Tempting
Since JDK 1.1 we have a quick, simple and tempting tool within the Core Language to create our own memory leaks. It doesn't matter whether we build server or standalone applications. This tool is called Inner Class. Together with its twin Anonymous Class both are very efficient in creating memory leaks.
public class Outer {
class Inner {
}
}How is this?
Every non-static Inner Class has an implicit reference to its surrounding class. Anonymous Classes are similar. To successfully create a memory leak simply pass an Inner Class object to a method which keeps references to the provided objects and you're done.
Why?
Suppose you implement something like a cache. Next follow the execution path to a local object which stores some of its inner class objects into the cache. After the local object was out of scope, it won't be garbage collected anymore! The inner class object in the cache holds a reference to the surrounding object and that one is still referenceable and therefore not a candidate for garbage collection anymore. The same is true for anonymous classes!
How to prevent this style of Memory Leaks?
- If you're about to use Inner Classes or Anonymous Classes think carefully. Don't use Anonymous Classes until you're very sure and can prove that they are not causing a Memory Leak.
- Use a static Inner Class to get rid of the implicit outer class reference.