【发布时间】:2015-04-17 14:28:23
【问题描述】:
下面的代码会分配很大的直接内存但不会导致java.lang.OutOfMemoryError: Direct buffer memory :
//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: Direct buffer memory。 我已经从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);
}
}
}
为什么限制失败发生在第一个?
【问题讨论】: