Thursday, June 30, 2005

Java - Memory Leaks

Now that we are talking Java, why not continue the discussion a little further, and since we ended on pointers in Java, the next question would be - what are memory leaks in Java, and why does it occur if Java performs its own garbage collection?

This is how the garbage collector in java works - starting at the root class and parsing through all nodes being referenced, at the same time keeping track of which objects are actively being referenced. Any classes no longer being referenced are then eligible to be garbage collected. What is to be noted is that an object is only counted as being unused when it is no longer being actively referenced. One other thing to keep in mind is that, unlike other languages such as C++, allocated memory is returned to the operating system when the application is closed.

Some common causes of memory leaks -
* Register a class as a listener, without unregistering it when it is no longer needed
Until the application receives event notification, the JVM will not garbage collect the storage.
* Declare a huge collection to be static
Collections hold other reference objects, and making them static keeps them in memory throughout the lifetime of the application.
* Not closing database or network connections
It is very important that the database or network collection is released once the information exchange is completed.
* Including native code in a Java program
The storage for references created in native C or C++ coding environments is not handled or garbage collected by the JVM. Hence the JNI memory must be directly dereferenced by the native language it was written in.

Now I know why I keep forgetting things nowadays. Lots of static HashMaps and Vectors pervading my brain!

No comments: