下面的代码将分配大量的直接内存,但不会导致java.lang.OutOfMemoryError:直接缓冲内存:
//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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但代码下面的代码将获得java.lang.OutOfMemoryError:直接缓冲内存.我已经看到了Java不安全内存分配限制的答案,但ByteBuffer.allocateDirect是使用Unsafe.allocateMemory()实现的.
//JVM args: -Xms10m -Xmx10m -XX:MaxDirectMemorySize=10m
public class DirectMemoryOOM {
public static …
Run Code Online (Sandbox Code Playgroud)