calum.org:~#

Monitoring PermGen usage

Tags: permgen java rest tomcat

Added: 2012-10-13T21:29:51

Monitoring PermGen usage

java.lang.OutOfMemoryError: PermGen space

If you use Tomcat, and redeploy your webapps quite often, you'll probably have hit the "Out of Permgen" memory message.

When that happens, restarting Tomcat is the only solution. (I suppose ideally you should do it every time you deploy, but it's faster not to, and I'm lazy.) Sometimes though, when you've hit this Permgen limit, Tomcat doesn't shutdown nicely, so you end up having to kill -9 it.

To avoid this, you need to restart it before it gets to be a problem. My quick-and-dirty solution is to script a check, and restart when it gets close to the limit.

This is a quick REST resource which returns the permgen percentage:

@Path("1.0")
public class PermgenBean implements PermgenResource {

    @GET
    @Path("permgen")
    @Produces("application/json")
    @Override
    public Response getPermgen() {
        final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (final MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
            if ("Perm Gen".equals(memoryPoolMXBean.getName())) {
                final MemoryUsage memoryUsage = memoryPoolMXBean.getUsage();
                final float percent = (100f / memoryUsage.getMax()) * memoryUsage.getUsed();
                return Response.ok().entity(percent).build();
            }
        }
        return Response.serverError().build();
    }
}

Add this to a script, and call it every 5 minutes from a cronjob:
#!/bin/bash
output=`curl -s http://your.server.name/rest/1.0/permgen`
if ( echo ${output} | grep "^9" > /dev/null )
then
  /etc/init.d/tomcat6 restart
fi

Very quick and dirty, and can result in your Tomcat instance restarting when you're not expecting it. However, if it's close to the point where it'll stop responding (correctly, or at all), it's the lesser of two evils.

posted by Calum on 2012-10-13T21:44 under

Add a comment

Your IP:
Please enter 9572567 here: