Soy consciente de que cada objeto requiere memoria de montón y cada primitiva / referencia en la pila requiere memoria de pila.
Cuando intento crear un objeto en el montón y no hay suficiente memoria para hacerlo, la JVM crea un java.lang.OutOfMemoryError en el montón y me lo arroja.
De manera implícita, esto significa que JVM reserva algo de memoria al inicio.
¿Qué sucede cuando esta memoria reservada se agota (definitivamente se agotaría, lea la discusión a continuación) y la JVM no tiene suficiente memoria en el montón para crear una instancia de java.lang.OutOfMemoryError ?
¿Simplemente se cuelga? ¿O me lanzaría un nulldado que no hay memoria para newuna instancia de 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
}
==
¿Por qué la JVM no puede reservar suficiente memoria?
No importa cuánta memoria esté reservada, aún es posible que esa memoria se use si la JVM no tiene una forma de "reclamar" esa memoria:
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
}
}
}
}
}
}
O más concisamente:
private void OnOOM(java.lang.OutOfMemoryError e) {
try {
e.printStackTrace();
} catch (java.lang.OutOfMemoryError e2) {
OnOOM(e2);
}
}
OutOfMemoryExceptiony luego hacer algo que implicó la creación de un buffer de gran tamaño ...
OutOfMemoryErrory retuvo una referencia al mismo. Resulta que atrapar un OutOfMemoryErrorno es tan útil como uno podría pensar, porque no puede garantizar casi nada sobre el estado de su programa al atraparlo. Ver stackoverflow.com/questions/8728866/…
