DirectMemory容量可通过-XX:MaxDirectMemorySize指定,如果不指定,则默认与Java堆的最大值(-Xxm指定)一样。下面的例子直接通过反射获取Unsafe实例并进行内存分配。
例:
package jvm;
import java.lang.reflect.Field;
/**
* -XX:MaxDirectMemorySize=10M
*
* @author Poison
*
*/
class DirectMemoryOOM {
private static final int _1MB = 1024 * 1024;
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
Field unsafeField = sun.misc.Unsafe.class.getDeclaredFields()[0];
unsafeField.setAccessible(true);
sun.misc.Unsafe unsafe = (sun.misc.Unsafe) unsafeField.get(null);
while (true) {
unsafe.allocateMemory(_1MB);
}
}
}
运行结果:
Exception in thread “main” java.lang.OutOfMemoryError
at sun.misc.Unsafe.allocateMemory(Native Method)
at jvm.DirectMemoryOOM.main(DirectMemoryOOM.java:19)