java.lang.OutOfMemoryError: Permgen space

Java applications are allowed to use only a limited amount of memory. The exact amount of memory your particular application can use is specified during application startup. To make things more complex, Java memory is separated into different regions as seen on the following diagram:

java.lang.outofmemoryerror: Permgen space

 

The size of all those regions, including permgen area, is set during the JVM launch. If you do not set the sizes yourself, platform-specific defaults will be used.

So – the “java.lang.OutOfMemoryError: PermGen space” message indicates that the Permanent Size area in memory is exhausted.

Cause of java.lang.OutOfMemoryError

To understand the cause for the “java.lang.OutOfMemoryError: PermGen space“, we need to start by reminding that everything in Java is represented as an Object. Also, all objects are instances from a specific Class. Even the Class declarations themselves are ultimately just very specific Objects. But what makes the class declarations interesting is the fact that on most JVMs Class declarations are loaded into a specific memory region, named Permanent Generation (PermGen for short).So – to recap: all Java classes are loaded and stored in the Java PermGen. This consists of the following:

  • Names of the classes
  • Fields of the class
  • Methods of a class with the bytecode of the methods
  • Constant pool information
  • Object arrays and type arrays associated with a class
  • Just In Time compiler optimizations

That’s pretty much it. Some more bits and pieces but it does not impact the actual memory consumption by more than few percent. All of these are allocated to PermGen and stay in PermGen.

As you can see, the PermGen size requirements depend both upon the number of classes loaded as well as the size of such class declarations. So it is easy to see the main cause for the “java.lang.OutOfMemoryError: PermGen space“: either too many classes or too big classes are being loaded to the permanent generation.

Most often such errors are triggered during the redeploy operations. When you are redeploying an application you are trying to get rid of the previous classloader referencing all the previously loaded classes and replace it with a classloader loading new versions of the classes. Unfortunately many libraries used within applications make it impossible to throw away the old classloader which means that during each redeploy all the previous versions of your classes will still reside in PermGen and consume the memory.

Examples of java.lang.OutOfMemoryError

Trivial example

As seen in the causation section, PermGen space usage is strongly correlated with the number of classes loaded into the JVM. The following code serves as the most straightforward example:


import javassist.ClassPool;

public class MicroGenerator {

	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 100_000_000; i++) {
			generate("eu.plumbr.demo.Generated" + i);
		}
	}

	public static Class generate(String name) throws Exception {
		ClassPool pool = ClassPool.getDefault();
		return pool.makeClass(name).toClass();
	}
}

In this example the source code is iterating over a loop and generating classes at the runtime. Class generation complexity is taken care by the javassist library.

Launching the code above will keep generating new classes and loading their definitions in Permgen space until the space is fully utilized and the “java.lang.OutOfMemoryError: Permgen space” is thrown.

Realistic example

As bit more complex and more realistic example, I demonstrate to you a “java.lang.OutOfMemoryError: Permgen space” error occurring during a redeploy. To reproduce this error yourself, download a demo application bundled with Plumbr, a memory leak detector tool. When running the demo application and attempting a redeploy with Plumbr attached, Plumbr will find a memory leak, similar to the following:

permgen-leak-example

The report highlights the org.hsqldb.jdbcDriver class, held in java.sql.DriverManager. When the application is started, the initializing code loads the HSQL JDBC driver org.hsqldb.jdbcDriver to connect to the database. Corresponding to specification, this JDBC driver registers itself with java.sql.DriverManager. This registration includes storing a reference to an instance of org.hsqldb.jdbcDriver inside a static field of DriverManager.

Now, when the application is undeployed from the application server, java.sql.DriverManager will still hold that reference. Apparently there is no code in neither the HSQLDB library, the Spring framework or in the application to remove it!

As a result, a jdbcDriver object holds a reference to org.hsqldb.jdbcDriver class which in turn holds reference to the instance of java.lang.Classloader used to load the application. And that ClassLoader still references all classes of the application. In case of this particular demo application, almost 2000 classes are loaded during application startup. These occupy roughly 12MB in PermGen. Which means that it would take about seven redeploys to fill PermGen and get the “java.lang.OutOfMemoryError: PermGen space” error message in your logs.

Can’t figure out what causes your OutOfMemoryError?
Read more.

Solution for java.lang.OutOfMemoryError

The first solution to the OutOfMemoryError due to PermGen should be obvious. If we have exhausted the PermGen area in the memory we need to increase its size. This solution is indeed helpful if you just have not given your JVM enough elbow room. So alter your application launch configuration and add (or increase if present) the following:

-XX:MaxPermSize=512m

This configuration parameter is indicating to the JVM that PermGen is allowed to grow up to 512 MB before complaining in the form of OutOfMemoryError.

Second possibility is to allow GC to unload classes from PermGen. The standard JVM is rather conservative in this regard – Classes are born to live forever. So once loaded, classes stay in memory even if no one is really using them anymore.

This can become a problem when the application is creating lots of classes dynamically and the generated classes are not needed for longer periods. In such a case, allowing JVM to unload class definitions can be helpful. This is achieved by adding again just one configuration parameter to your startup scripts:

-XX:+CMSClassUnloadingEnabled

By default this is set to false and so to enable this you need to explicitly set the following option in Java options. If you enable CMSClassUnloadingEnabled, GC will sweep PermGen too and remove classes which are no longer used. Keep in mind that this option will work only when UseConcMarkSweepGC is also enabled using the below option. So when running parallel or, God forbid, serial GCs, make sure you have set your GC to CMS by specifying:

-XX:+UseConcMarkSweepGC

But before calling it a night, be warned – more often than not usage of the recommended “quick fixes” means you are just masking the symptoms by hiding “java.lang.OutOfMemoryError: Permgen space” and are not tackling the underlying problem.

For example, if you really want to fix the leakage in PermGen we introduced in the examples section, the following servlet context listener can be used:

public class JdbcDriverLeakPreventer implements ServletContextListener {
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    //Nothing to do
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    ClassLoader applicationClassLoader = this.getClass().getClassLoader();
    Enumeration driverEnumeration = DriverManager.getDrivers();
    while (driverEnumeration.hasMoreElements()) {
      Driver driver = driverEnumeration.nextElement();
      ClassLoader driverClassLoader = driver.getClass().getClassLoader();
      if (driverClassLoader != null 
          && driverClassLoader.equals(applicationClassLoader)){
        try {
          DriverManager.deregisterDriver(driver);
        } catch (SQLException e) {
          e.printStackTrace(); //TODO Replace with your exception handling
        }
      }
    }
  }
}

This Servlet listener should be registered, for example, in the web.xml file of your application:

<listener>
    <listener-class>user.package.JdbcDriverLeakPreventer</listener-class>
</listener>

There are several ways to find out what has occupied the PermGen space in your JVM and whether the objects had a valid reason to fill it up. Memory dump analyzers, profilers, debuggers – the choice is yours. But if you need to be sure your PermGen is not filled up by garbage from a memory leak we can only recommend using Plumbr and finding it out for free.

Can’t figure out what causes your OutOfMemoryError?
Read more.