Monday, January 21, 2008

Does java have memory leak?

According to the IBM's artical, JAVA also has problems of memory leak event though they have its own memory garbage collector. The main reason is that: design is not good.

I. How memory garbage collector work?

The job of the garbage collector is to find objects that are no longer needed by an application and to remove them when they can no longer be accessed or referenced. The garbage collector starts at the root nodes, classes that persist throughout the life of a Java application, and sweeps though all of the nodes that are referenced. As it traverses the nodes, it keeps track of which objects are actively being referenced. Any classes that are no longer being referenced are then eligible to be garbage collected. The memory resources used by these objects can be returned to the Java virtual machine (JVM) when the objects are deleted.

II. How it leaks?

"An object is only counted as being unused when it is no longer referenced" ==> The garbage collector can not do its job if an object is referenced by others object for a very long time even though it is no longer needed. It can lead to a terrible problems: out of memory.

Example:

Object A = new Object; //A exists until program terminate.
During program life cycle, an object B is created and referenced by A
Because programmer believe in garbage collector, so they do not free memory manually,
but let garbage collector do it for him ==> B exist until A freed.
If program create many and many B for its life ==> all B will exist too ==> cause out of memory.

It is the obvious example of problem of memory leak. So we do not believe in Garbage Collector 100%. Let free object manually by assigned unused object to nil.


III.Preventing memory leaks

You can prevent memory leaks by watching for some common problems. Collection classes, such as hashtables and vectors, are common places to find the cause of a memory leak. This is particularly true if the class has been declared static and exists for the life of the application.

Another common problem occurs when you register a class as an event listener without bothering to unregister when the class is no longer needed. Also, many times member variables of a class that point to other classes simply need to be set to null at the appropriate time.

Hope i can help you in avoid memory leak in java.

Google