Identify memory leak in Java app

Posted by Vincent Ma on Oracle Blogs See other posts from Oracle Blogs or by Vincent Ma
Published on Sun, 2 Dec 2012 15:23:34 +0000 Indexed on 2012/12/02 17:15 UTC
Read the original article Hit count: 334

Filed under:

One important advantage of java is programer don't care memory management and GC handle it well. Maybe this is one reason why java is more popular.

As Java programer you real dont care it? After you meet Out of memory you will realize it it’s not true.

Java GC and memory is big topic you can get some information in here

Today just let me show how to identify memory leak quickly.

Let quickly review demo java code, it’s one kind of memory leak in our code, using static collection and always add some object.

import java.util.ArrayList;
import java.util.List;

public class MemoryTest {
public static void main(String[] args) {
new Thread(new MemoryLeak(), "MemoryLeak").start();
}
}

class MemoryLeak implements Runnable {
public static List<Integer> leakList = new ArrayList<Integer>();
public void run() {
int num =0;
while(true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
num++;
Integer i = new Integer(num);
leakList.add(i);

}
}
}

run it with java -verbose:gc -XX:+PrintGCDetails -Xmx60m -XX:MaxPermSize=160m MemoryTest

after about some minuts you will get

Exception in thread "MemoryLeak" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at MemoryLeak.run(MemoryTest.java:25)
at java.lang.Thread.run(Thread.java:619)
Heap
def new generation total 18432K, used 3703K [0x045e0000, 0x059e0000, 0x059e0000)
eden space 16384K, 22% used [0x045e0000, 0x0497dde0, 0x055e0000)
from space 2048K, 0% used [0x055e0000, 0x055e0000, 0x057e0000)
to space 2048K, 0% used [0x057e0000, 0x057e0000, 0x059e0000)
tenured generation total 40960K, used 40959K [0x059e0000, 0x081e0000, 0x081e0000)
the space 40960K, 99% used [0x059e0000, 0x081dfff8, 0x081e0000, 0x081e0000)
compacting perm gen total 12288K, used 2083K [0x081e0000, 0x08de0000, 0x10de0000)
the space 12288K, 16% used [0x081e0000, 0x083e8c50, 0x083e8e00, 0x08de0000)
No shared spaces configured.

OK let us quickly identify it using JProfile

Download JProfile in here 

Run JProfile and attach MemoryTest get largest size of  Objects in Memory View in here is Integer


then select Integer and go to Heap Walker.

get GC Graph for this object


 Then you get detail code raise this issue quickly now.

 That is enjoy it.

© Oracle Blogs or respective owner

Related posts about /Java /Java EE