Out of memory exception in Java

In this article, I will show you how to debug the beloved java.lang.OutOfMemoryError (aka OOM) errors using -XX:+HeapDumpOnOutOfMemoryError. You might wonder what will happen when this parameter will be added? Suprise, surprise. It makes heap dump on out of memory error.

Can we use politics to fill up memory?

To produce OOM in Java we just need to do something stupid. This is exactly how it can be done on the production system as well. Let’s practice on some non-optimal code.

It’s good to fail fast when we’re doing it wrong.

Lately, PCs have more than 64KB of memory and we don’t want to wait until “politics” strings are going to fill up gigabytes of memory. Let’s tweak the Xmx parameter a little to limit JVM memory up to 16 MB (-Xmx16m) and the mentioned argument (-XX:+HeapDumpOnOutOfMemoryError). Run.

Works! In the response, we can see that the dump file has been generated. The important part is that we are getting the entire memory dump from the exact moment of the OOM. The timing is important here because the OOM exception can be thrown by any fragment of the code so it’s in most cases useless.

What to do with .hprof file?

Let’s open the file with VisualVM.

We can see that instances of ApiRequest are taking 70.1% of the memory space and 96.4% instances. On the production environment is not always obvious why some of the objects are taking so much space but it’s invaluable help in tracing where we have the original problem. Usually, some of the objects are just vacuuming the free space.