我知道每个对象都需要堆内存,而堆栈上的每个基本/引用都需要堆栈内存。
当我尝试在堆上创建对象并且没有足够的内存来执行此操作时,JVM 在堆上创建一个java.lang.OutOfMemoryError并将其扔给我。
因此,隐式地,这意味着JVM在启动时会保留一些内存。
当此保留的内存用完(肯定会用完,请阅读下面的讨论)并且JVM堆上没有足够的内存来创建java.lang.OutOfMemoryError实例时,会发生什么?
它只是挂了吗?还是null
因为new
OOM实例没有存储空间而将其扔给我?
try {
Object o = new Object();
// and operations which require memory (well.. that's like everything)
} catch (java.lang.OutOfMemoryError e) {
// JVM had insufficient memory to create an instance of java.lang.OutOfMemoryError to throw to us
// what next? hangs here, stuck forever?
// or would the machine decide to throw us a "null" ? (since it doesn't have memory to throw us anything more useful than a null)
e.printStackTrace(); // e.printStackTrace() requires memory too.. =X
}
==
JVM为什么不能保留足够的内存?
无论保留了多少内存,如果JVM无法“回收”该内存,则仍然有可能用完该内存:
try {
Object o = new Object();
} catch (java.lang.OutOfMemoryError e) {
// JVM had 100 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
// JVM had 99 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e3) {
// JVM had 98 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e4) {
// JVM had 97 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e5) {
// JVM had 96 units of "spare memory". 1 is used to create this OOM.
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e6) {
// JVM had 95 units of "spare memory". 1 is used to create this OOM.
e.printStackTrace();
//........the JVM can't have infinite reserved memory, he's going to run out in the end
}
}
}
}
}
}
或更简而言之:
private void OnOOM(java.lang.OutOfMemoryError e) {
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
OnOOM(e2);
}
}
OutOfMemoryException
,然后做一些涉及创建大缓冲区的事情……
OutOfMemoryError
并保留了对它的引用时,才会发生这种情况。这说明捕获a OutOfMemoryError
并不像人们想象的那样有用,因为您几乎不能保证捕获程序的状态。见stackoverflow.com/questions/8728866/...