08
What is a memory leak ?
A « memory leak » (cf. http://en.wikipedia.org/wiki/Memory_leak) is a situation when program is unable to release memory it has acquired. It happens when objects are hard referenced by other objects so that JVM can’t release them.
Example
public class MemoryLab {
//a collection (a business cache for example) static HashSet<Integer> aCache = new HashSet<Integer>();public static void memoryLeak(int iter) {
Random random = new Random();
for (int i=0; i<iter; i++) {
int object = random.nextInt();//an object
aCache.add(new Integer(object));//this object is cached (e.g add in a collection), this way we make an hard reference
//do stuff with object ...
object=null;//we think object is release but in fact an hard reference exists in cache collection so that garbage can't realease it
}
//code
}
}
How can we see it ?
We can feel it in analyzing heap memory evolution with Jconsole or better VisualVM. The heap is growing because objects can’t be garbaged (cf MemoryLeak.jpg)
Analyze memory heap
When we observe this situation on heap memory, it’s time to make an heap dump (cf. http://opensides.wordpress.com/2010/03/05/heapdump/).
Trigger heap dump in hprof format
jmap -dump:format=b,file=dump.hprof <PID>
Analyze dump with MAT (Eclipse Memory Analyzer)
(cf. download Eclipse Memory Analyzer http://www.eclipse.org/mat/downloads.php)
File->Open Heap Dump … and select your file « dump.hprof »
MAT analyze for you the leak candidates( see diagram below)
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often. Thumbs up!
Fahter of the Bride Speeches…
[...]Memory leak « Java EE performance[...]…