JVM has provided helpful arguments to deal with OutOfMemoryError. Those JVM arguments are:
- -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath
- -XX:OnOutOfMemoryError
- -XX:+ExitOnOutOfMemoryError
- -XX:+CrashOnOutOfMemoryError
In order to diagnose OutOfMemoryError or any memory related problem, one would have to capture heap dump right at the moment or few moments before the application starts to experience OutOfMemoryError. It’s hard to do capture heap dump at the right moment manually because we will not know when OutOfMemoryError is going to be thrown. However, capturing heap dumps can be automated by passing following JVM arguments when you launch the application in the command line:
-XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath={HEAP-DUMP-FILE-PATH}
Example:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/crashes/my-heap-dump.hprof
In ‘-XX:HeapDumpPath’ you need to specify the filepath where heap dump should be stored.
When you pass these two JVM arguments, heap dumps will be automatically captured and written to a specified file path, when OutOfMemoryError is thrown.
Once heap dumps are captured, you can use tools like HeapHero, Eclipse MAT to analyze heap dumps.