让 JVM 抛出一个 OutOfMemoryError 内存溢出错误

本机内存溢出

DirectMemory容量可以通过-XX:MaxDirectMemorySize指定。

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public classDirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) throws IllegalArgumentException,
            IllegalAccessException {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeField.get(null);

        while (true) {
            try {
                unsafe.allocateMemory(_1MB);
            } catch (OutOfMemoryError er) {
                System.out.println(er.toString());
                System.exit(0);
            }
        }
    }
}

// java.lang.OutOfMemoryError

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注