如何使用Jemalloc跟踪JVM堆外内存泄漏

发布时间 2023-12-12 11:19:32作者: 方东信

编译和安装jemalloc

git clone https://github.com/jemalloc/jemalloc
git checkout stable-4
./autogen.sh
./configure --enable-perf
make
sudo make install

查看so装到哪儿去了

find -name *jemalloc.so

使用

启动jar之前设置下环境变量:
export LD_PRELOAD=/usr/local/lib/libjemalloc.so
export MALLOC_CONF=prof:true,lg_prof_interval:30,lg_prof_sample:17,prof_final:true
环境变量LD_PRELOAD用来替换原生的glibc malloc。 然后启动jar,运行一段时间,停掉后会生成多个jeprof.{processId}的文件,通过下面命令生成内存tracking信息:

jeprof --show_bytes --gif ~/jre/bin/java jeprof*.heap > ./app-profiling.gif

最后有将近95%的内存来自于jvm本身,也由于运行时间不是很长,所以可以认为是安全的,如果再持续一段时间这个百分比降低了,说明有内存泄露的可能。