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:

public class PermgenBean implements PermgenResource {

    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:
output=`curl -s`
if ( echo ${output} | grep "^9" > /dev/null )
  /etc/init.d/tomcat6 restart

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 9072630 here: