Wednesday, October 13, 2010

a simple tool to detect java over allocation

A while ago, I was exploring a memory leak (well, I thought it was a leak - but more on that later) , when I came across the problem of running memory analysis on a large, live application .
Sure, there are plenty of tools - MAT, and jvisualvm , to mention the best I've found - but it turned out these were too heavy-weight for me (the cost of dumping / transferring the heaps and/or running the GUI itself) .
what I've found useful, was to use simple multiple histograms obtained from jmap, and to use MySQL as the data analyzer. 
so , here are the very modest scripts (bash) :

import the histogram as a mysql table :
hisport
#!/bin/bash
MYSQL="mysql $DB"
FILE=$1
NAME=$2
if [ "$FILE" == "" ] || [ "$NAME" == "" ];then
    echo "usage : $0 <file> <name> - import jvm histogram <file> into table <name> using $DB"
fi
CLEAN=`mktemp`
cat $FILE | sed 's/\s\+/,/g' | cut -c2- > $CLEAN
$MYSQL  -e"create table $NAME (num int,inst int,mem int,name varchar(256));"
$MYSQL  -e"LOAD DATA LOCAL INFILE \"$CLEAN\" INTO TABLE $NAME FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' ignore 2 lines  (num,inst,mem,name);"


compare dead+live to live only objects  : this can hint on the type of objects which are being allocated and dropped over and over , i.e. garbage collected frequently (you should be able to get similar info from the gc itself , using -xlogcc or other JVM interfaces - what's nice about these scripts is that they can be ran on a live JVM without any pre-launch changes)
hispare
#!/bin/bash
MYSQL="mysql $DB"
dead=$1
live=$2
echo "select $dead.* ,$live.* ,$dead.inst - $live.inst diff from $live inner join $dead  on $dead.name=$live.name order by  diff DESC " | $MYSQL

putting it together:
# dump a live + dead histogram, import both and compare them :
$JAVA_HOME/bin/jmap -histo:live <pid> >pid.live.histo
$JAVA_HOME/bin/jmap -histo <pid> >pid.dead.histo
export DB=<DBNAME>
mysql -e"create database $DB"
./hisport pid.live.histo LIVE
./hisport pid.dead.histo DEAD
./hispare DEAD LIVE




No comments:

Post a Comment