当内存不足时会发生什么情况来抛出内存错误?
我知道每个对象都需要堆内存,堆栈上的每个基元/引用都需要堆栈内存。
当我尝试在堆上创建一个对象并且没有足够的内存来执行此操作时,JVM会在堆上创建一个java.lang.OutOfMemoryError并将其扔给我。
因此,隐含地,这意味着JVM在启动时保留了一些内存。
当这个保留内存用完时会发生什么(它肯定会用完,请阅读下面的讨论),并且JVM在堆上没有足够的内存来创建java.lang.OutOfMemoryError的实例?
它只是挂起了吗?或者他会扔给我一个,因为没有对OOM实例的记忆?null
new
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);
}
}