Metaspace, static fields and the String pool
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Three things in a Java program belong to classes rather than to one method call: the class's own description, its static fields and the string literals in its code. On HotSpot today they live in three different places, and older answers that put all of them in "PermGen" are out of date.
Metaspace: class metadata in native memory
Metaspace is the memory area, outside the heap, where the JVM keeps class information such as method code and field layouts.
Class metadata is the JVM's description of a loaded class: its methods and their bytecode, its field names and types, its constant pool and similar data. Metaspace is the native memory area where HotSpot keeps it, since Java 8.
Example 1 · Metaspace options and usage from the JDK tools
# Metaspace options and their defaults (macOS/Linux: use grep)java -XX:+PrintFlagsFinal -version | findstr Metaspace# How much Metaspace a running program usesjcmd <pid> GC.heap_info size_t MaxMetaspaceExpansion = 5439488 {product} {default}
uintx MaxMetaspaceFreeRatio = 70 {product} {default}
size_t MaxMetaspaceSize = 18446744073709551615 {product} {default}
size_t MetaspaceSize = 22020096 {product} {default}
size_t MinMetaspaceExpansion = 327680 {product} {default}
uintx MinMetaspaceFreeRatio = 40 {product} {default}
<pid>:
garbage-first heap total 120832K, used 2048K [0x000000008a600000, 0x0000000100000000)
region size 1024K, 2 young (2048K), 0 survivors (0K)
Metaspace used 148K, committed 384K, reserved 1114112K
class space used 6K, committed 128K, reserved 1048576KWhat this code does
- Real output from Java 21 on 64-bit Windows.
MaxMetaspaceSize = 18446744073709551615is the largest 64-bit number, meaning "no limit".MetaspaceSize = 22020096bytes (21 MB) is the first threshold for class unloading, not a maximum. jcmd <pid> GC.heap_infowas run on a small program that was only sleeping: the heap used 2 MB and Metaspace only 148 KB of class data, of which 6 KB was in the class space. Your numbers will differ.
Each class loader gets its own space there, and the class data is freed only when its class loader and all its classes become unreachable, which is called class unloading.
Before Java 8, HotSpot kept class metadata in PermGen (the permanent generation), an area with a fixed maximum size (-XX:MaxPermSize) that the garbage collector managed together with the heap. Programs that loaded many classes often died with OutOfMemoryError: PermGen space. Java 8 removed PermGen; Metaspace grows in native memory as needed.
class space line in the output below.Static fields live with the Class object on the heap
A static field has one value for the whole class, not one per object. Every loaded class has a java.lang.Class object, an ordinary object on the heap that HotSpot also calls the class mirror.
Example 2 · One static value shared by every object
import java.util.ArrayList;import java.util.List;
class Admission { static String college = "Govt Engineering College"; // one value for the whole class static int seatsFilled = 0; static final List<String> merit = new ArrayList<>(); // the list object is on the heap
String name;
Admission(String name) { this.name = name; seatsFilled++; merit.add(name); }}
public class StaticFieldsDemo { public static void main(String[] args) { Admission a1 = new Admission("Asha"); Admission a2 = new Admission("Bhavin"); Admission a3 = new Admission("Chitra");
Admission.college = "GEC Pune"; // change it once ... System.out.println(a1.name + " -> " + Admission.college); System.out.println(a3.name + " -> " + Admission.college);
System.out.println("Seats filled: " + Admission.seatsFilled); System.out.println("Merit list: " + Admission.merit);
Class<Admission> classObject = Admission.class; System.out.println(classObject.getName() + " is an instance of " + classObject.getClass().getName()); }}Asha -> GEC Pune Chitra -> GEC Pune Seats filled: 3 Merit list: [Asha, Bhavin, Chitra] Admission is an instance of java.lang.Class
What this code does
- Changing
Admission.collegeonce changes it for every admission, because there is only one copy, stored with theAdmissionclass'sClassobject. Each object has its ownname. meritis a static reference to anArrayListon the heap. The list keeps every name reachable for as long as the class is loaded.Admission.classis itself an object, an instance ofjava.lang.Class. On HotSpot that object is where the static values live.
On HotSpot, in Java 8 and later, the values of the static fields are stored inside that Class object. The field's description, its name and type, stays with the class metadata in Metaspace.
A static field of a reference type holds only a reference; the object it points to, such as a static ArrayList, is a normal heap object. A static field lives as long as its class stays loaded, which for application classes is usually the whole run. That is why a static collection that only grows keeps every element alive.
The String pool is on the heap
The String pool (the JVM's string table) is a table of unique String objects that lets equal texts share one object.
Example 3 · Which strings share one pooled object?
public class StringPoolDemo { public static void main(String[] args) { String a = "UPI-OK"; // literal: taken from the String pool String b = "UPI-OK"; String c = new String("UPI-OK"); // new: a separate object on the heap String d = c.intern();
String part = "UPI"; String e = part + "-OK"; String f = "UPI" + "-OK"; // two literals: joined by javac, so pooled
System.out.println("a == b " + (a == b)); System.out.println("a == c " + (a == c)); System.out.println("a == d " + (a == d)); System.out.println("a == e " + (a == e)); System.out.println("a == f " + (a == f)); System.out.println("a.equals(e) " + a.equals(e)); }}a == b true a == c false a == d true a == e false a == f true a.equals(e) true
What this code does
aandbare the same literal, so both refer to the one pooled object.new String(...)always makes a separate heap object, andintern()returns the pooled one again.part + "-OK"is computed while the program runs, so it builds a new, unpooled object."UPI" + "-OK"joins two literals, which javac does at compile time, so it is the same literal asa.equalscompares the text and istruefor all of them. Only==depends on pooling.
Every string literal in your code, such as "UPI-OK", refers to the pooled object, and intern() returns the pooled copy of any string, adding it if needed. Sharing is safe because strings cannot be changed.
Since Java 7, HotSpot keeps pooled strings on the ordinary heap; before that they were in PermGen. So the pool counts toward -Xmx, and pooled strings that nothing uses any more can be garbage collected like other objects. The Objects in Memory module looks at string memory and interning in more depth.
== compares references, so its result depends on pooling. Always compare text with equals.-XX:MaxMetaspaceSize and too many loaded classes
On HotSpot, Metaspace has no fixed limit by default: MaxMetaspaceSize is the largest possible number, so it can grow until the machine's memory runs low. -XX:MaxMetaspaceSize=256m sets a cap.
Example 4 · Loading the same class many times
import java.io.IOException;import java.io.InputStream;import java.lang.management.ManagementFactory;import java.lang.management.MemoryPoolMXBean;import java.util.ArrayList;import java.util.List;
class ReportTemplate { // the class we load again and again String render(int roll) { return "Report card for roll " + roll; }}
class OneClassLoader extends ClassLoader { private final byte[] bytes;
OneClassLoader(byte[] bytes) { super(null); // no parent: this loader defines the class itself this.bytes = bytes; }
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (!name.equals("ReportTemplate")) { throw new ClassNotFoundException(name); } return defineClass(name, bytes, 0, bytes.length); }}
public class ClassFloodDemo { static long metaspaceUsedKb() { for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { if (pool.getName().equals("Metaspace")) { return pool.getUsage().getUsed() / 1024; } } return -1; }
public static void main(String[] args) throws IOException, ClassNotFoundException { int copies = args.length > 0 ? Integer.parseInt(args[0]) : 2000; byte[] bytes; try (InputStream in = ClassFloodDemo.class.getResourceAsStream("ReportTemplate.class")) { bytes = in.readAllBytes(); }
long before = metaspaceUsedKb(); List<Class<?>> kept = new ArrayList<>(); // keeps every loader and class alive for (int i = 0; i < copies; i++) { kept.add(new OneClassLoader(bytes).loadClass("ReportTemplate")); } long after = metaspaceUsedKb();
System.out.println("Loaded " + kept.size() + " copies of ReportTemplate"); System.out.println("Metaspace used: " + before + " KB before, " + after + " KB after"); System.out.println("Same name? " + kept.get(0).getName().equals(kept.get(1).getName()) + ", same class? " + (kept.get(0) == kept.get(1))); }}Loaded 2000 copies of ReportTemplate Metaspace used: 741 KB before, 3609 KB after Same name? true, same class? false
What this code does
- Each
OneClassLoaderdefines its own copy ofReportTemplate. The copies have the same name but are different classes, and each one has its own class metadata in Metaspace: here 2000 copies used about 2.8 MB more. - The
keptlist keeps every class, and through it every class loader, reachable, so none of them can be unloaded. Without a limit, Metaspace simply grows. The numbers change from run to run.
Example 5 · OutOfMemoryError: Metaspace with a small cap
java -XX:MaxMetaspaceSize=16m ClassFloodDemo 100000Exception in thread "main" java.lang.OutOfMemoryError: Metaspace at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:889) at OneClassLoader.findClass(ClassFloodDemo.java:27) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:593) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526) at ClassFloodDemo.main(ClassFloodDemo.java:51)
What this code does
- With a 16 MB cap and up to 100,000 copies to load, Metaspace fills up after a few thousand classes and
defineClassfails. Real output from Java 21. - The message names the area that ran out:
Metaspace, notJava heap space. Raising-Xmxwould not help; the fix is to stop loading endless classes or to let old class loaders become unreachable.
When Metaspace reaches the cap and the garbage collector cannot unload enough classes, the JVM throws OutOfMemoryError: Metaspace.
Normal programs load a few thousand classes and use tens of MB. The trouble comes from code that keeps creating classes and keeps their class loaders reachable: frameworks that generate proxy classes on the fly, scripting engines that compile each script to a class, or an application server that redeploys an app many times while something still refers to the old class loader.
-XX:MetaspaceSize is not a size limit. It is the level of class data (about 21 MB by default on Java 21) at which the JVM first runs a collection that can unload classes.Next step
Check your understanding
12 quick questions