java.lang.OutOfMemoryError: Java heap space With Examples

java.lang.OutOfMemoryError is thrown when JVM is unable to allocate memory to create an object. Java OutOfMemoryError is an Error and occurs a runtime.


As the name suggests, OutOfMemoryError occurs when java runtime is out of memory. In this case garbage collector is unable to free more space required by program and hence error is thrown.

There are two main reasons to get java.lang.OutOfMemoryError:

  1. Poor programming – infinite loop, not clearing memory by closing resources etc.
  2. Low Memory – java is running on less memory than required.

Java OutOfMemoryError – Poor Programming Example

Let’s look into a sample code that will throw java.lang.OutOfMemoryError: Java heap space because the program is going into infinite loop and objects are getting created but not getting garbage collected. So eventually JVM will run out of memory.

When above code is executed, it will throw following exception after some time.

This is an example of poor programming, but the good news is that the exception stack trace clearly points us to look for the code where this error occurred. However sometimes the problem might be in some other areas of the program, in that case we will need help of java profilers such as VisualVM to figure out where most of the memory is being allocated and how to optimize it.

Java OutOfMemoryError – Low Memory Example

Let’s look at another example where the OutOfMemoryError is caused because we didn’t allocate enough memory for program to execute properly.

Let’s see what happens when we run above program with JVM max memory limit of 32 MB.

As we can see that there is nothing wrong in the program, we are running it on very low memory. Let’s try to fix this OutOfMemoryError by increasing the JVM memory to 256MB and then 512 MB.

So it seems that our program runs fine when we provide enough memory to run it.

Increasing the memory of JVM is a quick fix to solve the problem, unless you are running on very low memory. If you are already running on high JVM memory such as 2GB or more, then you should look into the application code to optimize it, look into thread dump and java profiler output to see why your application requires high memory and if you can reduce it.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: