五 5.2 — 方法区溢出Demo以及解决OOM的一些途径
学习渠道:尚硅谷
1.OOM Demo
/**
* jdk7:
* -XX:PermSize=10m -XX:MaxPermSize=10m
* jdk8:
* -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
*
* 其他的例子:借助cglib是的方法区出现内存溢出异常也可以实现OOM
*/
public class NonHeapOOMTest extends ClassLoader{
public static void main(String[] args) throws Exception{
int j = 0;
try {
//ClassLoader test = ClassLoader.getSystemClassLoader();
NonHeapOOMTest test = new NonHeapOOMTest();
for(int i = 0 ; i < 10000 ; i++){
//创建ClassWriter对象, 用于生成类的二进制字节码
ClassWriter writer = new ClassWriter(0);
writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class" + i
, null, "java/lang/Object", null);
//返回byte[]
byte[] code = writer.toByteArray();
//类的加载
test.defineClass("Class" + i, code, 0, code.length);
j++;
}
} finally {
System.out.println("j = " + j);
}
}
}