Sunday, May 29, 2016

How to analyze native memory leak in Java

Memory leak on heap is easy but how can I analyze native memory leak in Java?

You can use `jemalloc` for this purpose.

Install `jemalloc`:

wget https://github.com/jemalloc/jemalloc/releases/download/4.2.0/jemalloc-4.2.0.tar.bz2

bzip2 -d jemalloc-4.2.0.tar.bz2
tar xvf jemalloc-4.2.0.tar

cd jemalloc-4.2.0
./configure --prefix=/home/izeye/programs/jemalloc --enable-prof
make
make install

Profile your application just by running it with the following environment variables:

export LD_PRELOAD=/home/izeye/programs/jemalloc/lib/libjemalloc.so
export MALLOC_CONF=prof_leak:true,lg_prof_sample:0,prof_final:true

Create a report with the following command:

/home/izeye/programs/jemalloc/bin/jeprof --show_bytes --svg `which java` jeprof.65301.0.f.heap > result.svg

Now you can spot the leaking point by seeing the result.

In my case, the culprit was Deflater. More precisely it was me. I missed to call `end()` to release the native resources.

References:
http://www.evanjones.ca/java-native-leak-bug.html
https://gdstechnology.blog.gov.uk/2015/12/11/using-jemalloc-to-get-to-the-bottom-of-a-memory-leak/
https://github.com/jemalloc/jemalloc/releases
https://github.com/jemalloc/jemalloc/wiki/Use-Case%3A-Leak-Checking

No comments:

Post a Comment