下面的代码将分配的直接内存大大小,但不会导致java.lang.OutOfMemoryError:直接缓冲存储器:为什么XX:MaxDirectMemorySize不能限制Unsafe.allocateMemory?
//JVM args: -Xms10m -Xmx10m -XX:MaxDirectMemorySize=10m
public class DirectMemoryOOM {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Field f = Unsafe.class.getDeclaredFields()[0];
f.setAccessible(true);
Unsafe us = (Unsafe) f.get(null);
long size = 1024 * 1024 * 1024;
while (true) {
long p = us.allocateMemory(size);
for (int i = 0; i < size; i++) {
us.putByte(p + i, Byte.MAX_VALUE);
}
}
}
}
但代码下面的代码将得到java.lang.OutOfMemoryError:直接缓冲存储器。 我已经看到了Java unsafe memory allocation limit答案,但ByteBuffer.allocateDirect使用Unsafe.allocateMemory()
//JVM args: -Xms10m -Xmx10m -XX:MaxDirectMemorySize=10m
public class DirectMemoryOOM {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
int size = 1024 * 1024;
System.out.println(sun.misc.VM.maxDirectMemory());
while (true) {
ByteBuffer.allocateDirect(size);
}
}
}
为什么限制无法发生的第一个实施?
感谢您的回答! –