This is a follow up question to What happens when there's insufficient memory to throw an OutOfMemoryError?
My question is the following: If an OutOfMemoryError
is preallocated (to avoid the situation of having insufficient memory for the OutOfMemoryError
object) and the JVM has to throw this type of error two times or more, then how can the preallocated object truthfully implement the getStackTrace
method?
If the same object is reused, then one of the objects will most likely have an invalid getStackTrace
, wouldn't it?
The key to the answer lies in the contract to
Throwable.getStackTrace()
:The
OutOfMemoryError
thrown is in fact not necessarily a preallocated one. If it has enough memory to allocated a newOutOfMemoryError
with a proper stack trace it will. But if it hasn't got memory it will use a preallocated one with no stack trace information. Such preallocated object can therefor be reused if anotherOutOfMemoryError
needs to be thrown.Modifying the (best) answer to the question you mentioned explains what is going on:
Output:
As can be seen in this answer to the other question the HotSpot JVM will actually pre-allocate
OutOfMemoryErrors
without any stack trace as well as a number of them with pre-allocated space to fill in a stack trace.