How to troubleshoot a JVM OutOfMemoryError problem
There aren’t any magical tools that will fix an OutOfMemoryError for you, but there are some options available that will help automate your ability to troubleshoot and identify the root cause.
Follow these three steps to deal with this JVM memory error and get on the way to recovery:
- Capture a JVM heap dump
- Restart the application
- Diagnose the problem
1. Capture the heap dump
A heap dump is a snapshot of what’s in your Java program’s memory at a given point in time. It contains details about objects that are present in memory, actual data that is present within those objects, references how those objects maintain to others objects and other information. A heap dump is a vital step to fix an OutOfMemoryError, but they do present some challenges, as their contents can be difficult to read and decipher.
In an optimal situation, you want to capture a heap dump at the moment of or just prior to an OutOfMemoryError to diagnose the cause, but this isn’t exactly easy. However, you can automate this heap dump process. Tell the JVM to create a heap dump by editing the JRE’s startup parameters with the following variables:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/crashes/my-heap-dump.hprof
2. Restart the troublesome application
Most of the time, an OutOfMemoryError won’t crash the application, but it could put the application in an unstable state. A restart would be a prudent move in this situation, since requests served from an unstable application instance will inevitably lead to an erroneous result.
And, you can automate this restart process as well. Simply write a “restart-myapp.sh” script, which will bounce your application. Provide command line arguments to the JVM that trigger it to run the following script when you encounter the exception:
-XX:OnOutOfMemoryError=/scripts/restart-myapp.sh
When you pass this argument, the JVM will invoke “/scripts/restart-myapp.sh” script whenever OutOfMemoryError is thrown. Thus, your application will be automatically restarted right after it experiences an OutOfMemoryError.
3. Diagnose the problem
Now that you have captured the heap dump — which is needed to troubleshoot the problem — and restarted the application — to reduce the outage impact — the next step is troubleshooting.
As mentioned above, understanding the contents of a heap dump can be tricky, but there are helpful heap analyzer tools that help simplify the process. Some options include Eclipse Memory Analyzer (MAT), Oracle JHat or HeapHero.
These tools generate a memory analysis report, highlight the objects that cause the most memory and hopefully help identify objects that create a memory leak.
It can be extremely frustrating when your applications encounter a runtime error. You’ll need patience, a memory heap dump and the proper tools to analyze the problem to fix the OutOfMemoryError and other pesky exceptions of a similar ilk.