Java触发Metaspace的OOMError

package comg.yang.httpstest;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;

/**
 * @description:
 * @author: Yang JianXiong
 * @since: 2023/5/1
 * <p>
 * VMOption:-XX:MetaspaceSize=10M -XX:MaxMetaspaceSize=10M
 */
public class MetaSpaceOOMTest extends ClassLoader {

    public static void main(String[] args) {
        int count = 0;
        MetaSpaceOOMTest metaSpaceOOMTest = new MetaSpaceOOMTest();
        for (int i = 0; i < 10000; i++) {
            //1.创建ClassWriter
            ClassWriter classWriter = new ClassWriter(0);
            
            //2.指定类的:Java版本号、类名、包名、父类、接口
            classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class_" + i, null, "java/lang/Object", null);
            
            //3.生成类的字节码
            byte[] byteArray = classWriter.toByteArray();
            
            //4.将类的字节码加载到虚拟机
            metaSpaceOOMTest.defineClass("Class_" + i, byteArray, 0, byteArray.length);

            System.err.printf("动态加载了 %d 个类\n", i);
            count++;
        }

        System.err.printf("动态加载了 %d 个类", count);
    }

}
posted @ 2023-05-02 23:57  JaxYoun  阅读(29)  评论(0编辑  收藏  举报