Memory Leaks in Java

One of the beauties of using Java programming language is that the programmers need not worry about the memory allocation and freeing of objects. We simply declare and initialize objects and JVM (Java Virtual Machine) will take care of freeing them when they are no longer in use by any application through a mechanism called ‘garbage collection’. Before we start our topic, let us check how the memory is allocated for the objects.

Generally, the objects which are created using the ‘new’ keyword are allocated in ‘memory heap’ and the objects that are used for the method arguments and method variables are created into a ‘stack’. When these objects are no more referred or when they are out of scope, they are eligible for garbage collection. The statement System.gc(); only suggest the JVM to perform a garbage collection and we can’t force the JVM to do it, but the JVM may do it when the system is running short of memory.

Though JVM manages the memory, we can’t be sure about the memory leaks. One can still have memory leak by poor programming (may be by keeping the references to null for too many objects in an application). If the Java program is written to run continuously in a server,even small memory leaking is risky. And a relatively small program also can reach the memory limit by using large number of temporary objects or objects that take large amount of memory. In such cases, Java holds memory for the unused objects and the application may run out of memory. JVM memory leaking is not dangerous as much as C++ memory leaking where the memory does not return to the operating system after the crash of the application. But in java programs, objects are created in the memory given to the JVM by the operating system. So when the JVM is closed, memory will return back to the OS.

If, there comes java.lang.OutOfMemoryError exception while executing a java application, your program may have memory leak. Finding the reason for memory leak can be difficult. By watching some of the common problems we can control the memory leaks. Some of the collection classes which is declared as static or which lives for the lifetime of an application such as hashmaps and vectors are common places where we can find memory leaks. Another common place is when we register an event listener toa class and forget to unregister it when it is not needed. We can use debugging tools like JProbe Suite, Optimizeit Enterprise Suite, Win32 Java Heap Inspector etc for fixing the memory leaks in java programming.