The "java.lang.OutOfMemoryError: Metaspace" or "java.lang.OutOfMemory: Permgen space" get thrown when the metaspace/permgen region of the JVM memory is exhausted.

Start your free trial

Classloader Leak

A classloader leak happens when an application is redeployed, but there are lingering instances of the previous deployment’s classes left. These lingering instances prevent their Classes from being garbage collected, which, in turn, prevent the classloaders and all the classes held therein from being collected, too. Here’s an example of that situation:

Apparently, the application starts a thread that cleans up connections. As noble of a goal as it is, the application does not stop the thread on un-deploy, so it keeps hold of the classloader. Cleanup threads and Timer threads are by far the most common reason for the leaks. A simple way of fixing this issue would be to add a shutdown hook by implementing a ServletContextListener:

public class CleanupCleanup implements ServletContextListener {
  public void contextDestroyed(ServletContextEvent sce) {
    // Stop the cleanup thread


Too Many Classes

Another common root cause of a Metaspace OOM are the dynamic languages. There’s nothing wrong with them inherently, but they give you a lot more weaponry to shoot yourself in the foot. In this case, Groovy was used to generate tens of thousands of classes occupying close to a gigabyte of space. There’s no generic way to fix this, as the issues are usually quite application-specific. Sometimes, the issue is in fact a runtime bug, so upgrading to a newer version is a good idea. For instance, groovy versions prior to 2.4.5 may trigger a JVM bug that prevents class unloading.

Start your free trial