Wednesday 3 February 2016

Basic understanding of Memory leaks

A memory leak occurs when object references that are no longer required are still maintained unnecessarily. However many times, it's difficult detect or difficult to interpret from the detected logs by any tool.

There are many reasons why the memory issues happen, however few primary reasons are


1. Java heap memory leaks- Java objects are created continuously without being released.

2. Native memory leaks - any continuously memory growing causing issues outside heap area.
3. Resource Constraints: If the available memory is too little to allocate or fragmented a lot that unable to allocate new objects.

Here we will discuss more about Heap Memory Issues.

The very basic symptom of a memory leak is outOfMemoryError. However all outOfMemoryError doesn't imply the memory leaks and all memory leaks doesn't come from outOfMemoryError issues.


Memory Leaks happen, When we are holding references to objects, preventing the Garbage Collector to clean them up.

Another potential source of these OOM issue arises with the use of Finalizers in a class. The objects of this type don't have their memory reclaimed, instead queued up for finalization post GC. If the finalizer thread cannot keep up with the finalization queue, then the Java heap could fill up causing an OOM.

The Straight forward method of finding memory leaks in application would be

1. Identify Symptoms.
2. Enable Verbose GC
3. Profiling
4. Analysis

1. Identify Symptoms. - When an OOM occurs, Need to identify if this is a normal memory exhaustion or a memory leak.


2. Enable Verbose GC -  One of the quickest ways to assert that you indeed have a memory leak is to enable verbose garbage collection. The -verbosegc argument allows you to generates a trace each time the garbage collection (GC) process is begun. That is, as memory is being garbage-collected, summary reports are printed to standard error, giving you a sense of how your memory is being managed.


3. Profiling- Different JVMs offer different ways to generate trace files to reflect heap activity, which typically include detailed information about the type and size of objects. This is called profiling the heap.

4. Analysis- The trace generated by the JVM comes in different format by different tools. However the analysis idea is same behind all. Find a block of objects that shouldn't be there and if these objects accumulate instead of releasing.

No comments:

Post a Comment