java本地内存直接溢出

DirectMemory容量可通过 -XX:MaxDirectMemorySize指定,如果不指定,则默认与java堆最大值一样,虽然使用DirectByteBuffer分配内存也会抛出内存溢出异常,但它抛出异常时并没有真正向操作系统申请分配内存,而是通过计算得知内存无法分配,于是手动抛出异常,真正申请分配内存的方法是unsafe.allocateMemory()
下面是测试代码:

public class DirectMemoryOOM{
	private static final int_1MB = 1024 * 1024;
	public static void main(String[] args) throws Exception{
		Field unsafeField = Unsafe.class.getDeclaredFields()[0];
		unsafeField.setAccessible(true);
		Unsafe unsafe = (Unsafe) unsafeField.get(null);
		while(true){
			unsafe.allocateMemory(_1MB);
		}
	}
}

执行报错:

Excepiton in thead "main" java.lang.OutOfMemoryError

猜你喜欢

转载自blog.csdn.net/fight252/article/details/91351098