Handling memory leaks in Java
Detecting Memory Leak in Java
Simple reason is for memory leaks in Java is due to poor application designs where garbage collector is unable to remove object references as they are referenced by static variables.
If you are getting java.lang.OutOfMemoryError that means either your Java heap does not have enough memory to create objects or there is a memory leak and there is not enough memory left to create more objects. Memory leak means the memory is not being reclaimed by the Garbage collector.
GC (garbage collector) tries to find objects that are no longer needed by an application, meaning that GC will remove objects when they are no longer being accessed or referenced. According to a paper from IBM “The garbage collector starts at the root nodes, classes that persist throughout the life of a Java application, and sweeps through 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.”
Well it is true that Java code does not require the programmer to be responsible for memory management cleanup, and that it automatically garbage collects unused objects. However, the key point to remember is that an object is only counted as being unused when it is no longer referenced.
How to detect memory leaks:
- Find and monitor Static Variables or Classes and profile them
- Use tools like Jprofiler, JProbe, OptimizeIt etc to detect memory leaks.
- Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems.
- Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime class. Place these calls in your code strategically for pre and post memory recording where you suspect to be causing memory leaks
