Mir ist bewusst, dass jedes Objekt Heapspeicher benötigt und jedes Grundelement / jede Referenz auf dem Stapel Stapelspeicher benötigt.
Wenn ich versuche, ein Objekt auf dem Heap zu erstellen, und nicht genügend Speicher vorhanden ist, erstellt die JVM einen java.lang.OutOfMemoryError auf dem Heap und wirft ihn mir zu.
Dies bedeutet implizit, dass beim Start von der JVM Speicher reserviert ist.
Was passiert, wenn dieser reservierte Speicher aufgebraucht ist (er würde definitiv aufgebraucht sein, siehe Diskussion unten) und die JVM nicht über genügend Speicher auf dem Heap verfügt, um eine Instanz von java.lang.OutOfMemoryError zu erstellen ?
Hängt es nur? Oder würde er mir einen werfen, nullda es keine Erinnerung an neweine Instanz von OOM gibt?
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
}
==
Warum konnte die JVM nicht genügend Speicher reservieren?
Unabhängig davon, wie viel Speicher reserviert ist, kann dieser Speicher immer noch verbraucht werden, wenn die JVM keine Möglichkeit hat, diesen Speicher "zurückzugewinnen":
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
}
}
}
}
}
}
Oder genauer:
private void OnOOM(java.lang.OutOfMemoryError e) {
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
OnOOM(e2);
}
}
OutOfMemoryException
OutOfMemoryErrorabfängt und einen Verweis darauf behält. Es stellt sich heraus, dass das Abfangen von a OutOfMemoryErrornicht so nützlich ist, wie man denkt, da Sie fast nichts über den Status Ihres Programms beim Abfangen garantieren können. Siehe stackoverflow.com/questions/8728866/…
