为了模拟java.lang.OutOfMemoryError: Metaspace,您必须加载许多不同的类。
首先必须设置以下元空间设置:
-XX:MaxMetaspaceSize=10m
-XX:MetaspaceSize=2M
-XX:MaxMetaspaceFreeRatio=1
-XX:MaxMetaspaceExpansion=1K
-XX:MinMetaspaceFreeRatio=1
-XX:InitialBootClassLoaderMetaspaceSize=2M
然后下面的代码让类加载器加载了很多不同的类。这是通过获取类的编译字节码mypackage.Myclass0并通过更改类名和调整类名的长度来调整以迭代地创建新类来实现的:
public static void main(String[] args) throws Exception {
String clazzBase64 ="yv66vgAAADcADAEAEm15cGFja2FnZS9NeWNsYXNzMAcAAQEAEGphdmEvbGFuZy9PYmplY3QHAAMBAApTb3VyY2VGaWxlAQANTXljbGFzczAuamF2YQEABjxpbml0PgEAAygpVgwABwAICgAEAAkBAARDb2RlACEAAgAEAAAAAAABAAEABwAIAAEACwAAABEAAQABAAAABSq3AAqxAAAAAAABAAUAAAACAAY=";
byte[] compiledClazz = Base64.getDecoder().decode(clazzBase64);
int classNameLength = Integer.valueOf(compiledClazz[12]);
MyClassLoader myClassLoader = new MyClassLoader(Thread.currentThread().getContextClassLoader());
for (int i = 0; ; i++) {
byte[] bytes = String.valueOf(i).getBytes();
byte[] bytecode = new byte[compiledClazz.length + bytes.length - 1];
System.arraycopy(compiledClazz, 0, bytecode, 0, 30);
bytecode[12] = (byte) (classNameLength + bytes.length - 1 & 0xFF);
System.arraycopy(bytes, 0, bytecode, 30, bytes.length);
System.arraycopy(compiledClazz, 31, bytecode, 30 + bytes.length, compiledClazz.length - 31);
String classname = "mypackage.Myclass" + i;
Class c = myClassLoader.getClass(classname, bytecode);
}
}
public static class MyClassLoader extends ClassLoader {
public MyClassLoader(ClassLoader parent) {
super(parent);
}
public Class<?> getClass(String name, byte[] code) {
return defineClass(name, code, 0, code.length);
}
}
梵蒂冈之花
芜湖不芜
相关分类