Kao
Kao

Reputation: 7364

Why PermGen is not populated faster?

I want to invoke OutOfMemoryError: PermGen space error as soon as possible.

I have created custom classloader:

public class MyClassLoader extends URLClassLoader {

private MyClassLoader(URL[] urls) {
    super(urls);
}

@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    if (name.equals("com.memory.leaks.Leak")) {
        return findClass(name);
    }

    return super.loadClass(name);
}

static IStructure newInstance() {

    try {
        final URL classSource = Structure.class.getProtectionDomain().getCodeSource().getLocation();

        try (URLClassLoader cl = new MyClassLoader(new URL[] { classSource })) { 
            return (ILeak) cl.loadClass("com.memory.leaks.Leak").newInstance();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

}

and here is a Leak class loaded by this classloader:

package com.memory.leaks;

public class Leak  {

}

This code will cause OOME already. Then I modified Leak class by adding 20 methods with very long names to it:

public void aaaaaaaaaaaaaaaa ...~ 50 chars... aaaaaaaa () {
}

Since method names reside in PermGen, such a modification should speed up populating PermGen. However, dynamic analysis (using JVisualVM with VisualGC) shows that it is being done with virtually the same speed:

Before modification (71s):

Before modification

After modification (69s):

After modification

My question is simple: Why?

Upvotes: 1

Views: 76

Answers (1)

Dunes
Dunes

Reputation: 40693

Why would having a method with a long name significantly increase the amount of space used by a class? The class loader will intern the method name, notice that the string already exists in memory and use that string rather than a new string.

If you want to increase the amount of space a class takes up then declare lots of static fields.

Upvotes: 2

Related Questions