DirectMemory可以通過-XX:MaxDirectMemorySize指定次询,如果不指定楚昭,默認與Java堆的最大值(-Xmx指定)一樣灿椅。
NIO會使用到直接內(nèi)存恨憎,你可以通過NIO來模擬,在下面的例子中验夯,跳過NIO猖吴,直接使用UnSafe來分配直接內(nèi)存。
代碼:
public class DrectMemoryOOM {
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);
}
}
}
虛擬機參數(shù):
-Xmx20M 最大堆內(nèi)存
-XX:MaxDirectMemorySize=10M 最大直接內(nèi)存
運行結(jié)果:
Exception in thread "main" java.lang.OutOfMemoryError
at sun.misc.Unsafe.allocateMemory(Native Method)
at com.example.outofmemoryerror.DrectMemoryOOM.main(DrectMemoryOOM.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
DirectMemory導致的內(nèi)存溢出挥转,一個明顯的特征是在Heap Dump文件中不會看見明顯的異常海蔽,如果發(fā)現(xiàn)OOM之后Dump文件很小,而程序中又直接或間接使用了NIO绑谣,就需要考慮是不是這方面的原因了党窜。