May 14, 2025
When the JVM is Out of Memory: Unraveling the Mystery of OutOfMemoryError Exception Creation

When the JVM is Out of Memory: Unraveling the Mystery of OutOfMemoryError Exception Creation

Java throws an OutOfMemoryError exception when JVM cannot allocate memory to an object because it is out of memory. But how the JVM is able to create an instance of the “OutOfMemoryError” object itself when it’s out of memory? 🤔

Trivial question. Isn’t it? Let’s find out the answer.

→ When the JVM runs out of memory, it can no longer create new objects.
→ However, it still needs to create an OutOfMemoryError object to let the application know that it has run out of memory.

🎯In JVM, there is mainly 2 (actually 3) types of memory

1) Heap memory: memory within the JVM process that is used to hold Java Objects and is maintained by the JVMs Garbage Collector.

2) Native memory/Off-heap: is memory allocated within the processes address space that is not within the heap and thus is not freed up by the Java Garbage Collector.

→ The native heap is usually much smaller than the Java heap.

→ To solve this problem, the JVM sets aside a small amount of memory (that is, native memory) at startup to hold a few essential objects, including the OutOfMemoryError object.

→ Basically, the instance of the OutOfMemoryError object is created when you start the JVM (say Java program) and will be re-used when there’s not enough memory in the Java heap.

Leave a Reply

Your email address will not be published. Required fields are marked *