OutOfMemoryError: Metaspace

java.lang.OutOfMemoryError: Metaspace

Quick Answer

The JVM ran out of metaspace, which stores class metadata. You are loading too many classes or have a classloader leak.

Why This Happens

Metaspace stores class definitions and metadata. This error occurs when too many classes are loaded, often from dynamically generating classes, having many classloaders, or redeploying web applications without proper cleanup. It replaced PermGen space in Java 8+.

The Problem

// Repeatedly creating classloaders without cleanup
while (true) {
    URLClassLoader loader = new URLClassLoader(new URL[]{jarUrl});
    loader.loadClass("com.example.Plugin");
    // Never closing the classloader
}

The Fix

// Close classloaders when done
try (URLClassLoader loader = new URLClassLoader(new URL[]{jarUrl})) {
    Class<?> clazz = loader.loadClass("com.example.Plugin");
    // Use the class
} // Automatically closed

Step-by-Step Fix

  1. 1

    Identify the class loading

    Use -verbose:class JVM flag to see which classes are being loaded. Look for repeated loading of the same classes.

  2. 2

    Check for classloader leaks

    In web apps, check for ThreadLocal leaks, JDBC driver registration, or static references that prevent classloader garbage collection.

  3. 3

    Fix the leak or increase metaspace

    Close classloaders properly, fix classloader leaks, or increase metaspace with -XX:MaxMetaspaceSize=256m.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free