Out of memory (OOM) error
JVM has different types of memory such as stack, heap etc. Heap memory is used by JVM to create and
managed lifecycle of java objects. String pool is also part of the heap memory only. String literals are
stored in string pool.
Out of memory error is thrown when there is insufficient space to allocate an object in the Java heap. In
this case, the garbage collector cannot make space available to accommodate a new object, and the
heap cannot be expanded further.
java.lang.OutOfMemoryError exception is thrown to indicate that heap memory is exhausted. This
exception can be thrown by java code or native library code when a native allocation cannot be satisfied.
Out of memory exception is having following format. Root cause says what the exact reason is to throw
OOM exception. Exception couldn’t be just because of heap space but other cases also. Hence first look
at root cause. For heap space, it’d be “Java heap space”
Exception in thread <thread_name> java.lang.OutOfMemoryError: <root cause>
Exception hierarchy of OutOfMemoryError exception
This exception is an exception like other exception. It is runtime exception and sub type of
VirtualMachineError which is in turn sub type of Error. Throwable is parent of all exceptions.
How it affects JVM?
Every exception thrown at runtime is finally handled by thread which is executing that code if not handle
anywhere in code. Same is applied to this exception. When JVM is not able to allocate space in heap
memory for object, it throws this exception. If not handled anywhere, it’s handled by thread which was
executing that piece of code and finally thread terminates. When thread is terminated, JVM frees all the
references thread was holding which ultimately leads to free of heap memory. JVM terminates itself if
there is no other running thread.
This exception can be handled to perform shutdown gracefully such as writing root cause of exception,
closing the resources etc.
Note – JVM doesn’t close the opened resource connection such as DB connection automatically when
thread is terminated. It’s developer’s responsibility to perform graceful shutdown of thread.
How to fix OOM heap space error?
Generally, we conclude that a thread which threw this exception is exhausting lot of heap space. But
there could be a chance that parent thread me exhaust lot of memory and child thread consumes few
bytes. As already lot of memory consumed by parent but execution is going on in child thread, it leads to
believe, child thread is culprit.
To fix such exception, either assign max heap space at the beginning of starting JVM or find out which
data is consuming lot of heap space and fix there.