You get out of memory, now what? First of all you need to understand what kind of OutOfMemory is it. You may run out of OS virtual memory, native memory allocated to Java process, or Java heap. The error message normally gives a good indication of specifics, see a few examples:
A typical Java process has a heap where Objects go into, which is also divided into different sections. Depending on the implementation of JVM they might be called: Eden Space (New), From Space (Survivor 1), To Space (Survivor 2), Old Generation (Tenured), and Perm Generation (it is considered outside Heap in some implementations). For a detailed explanation see this page or this page. On top it add memory required for class-loaders, garbage collection process, threads stack, JNI, native memory buffers, etc. For a detailed explanation see this page.
Here, I'm going to list what you need to know before analyzing an OutOfMemoryError:
1- What is the architecture of your machine and the JVM running your Java process: 32-bit, 64-bit, or else? How to proceed from here depends on answers to this question, because a 32-bit Java process is limited to about 3GB of usable virtual memory in user space with default settings, and 4GB in best case.
The commands above tell me that I'm running a 64-bit JVM on a 64-bin machine.
2- How much memory is allocated to the Java process?
The command above suggests that my Java process is allocated 3.4GB of memory by OS (VSZ) and is currently utilizing 0.8GB (RSS) of it.
3- How much memory is allocated to Java heap?
It says my Java process has 287MB in old generation (119MB used) and 200MB in perm generation (118MB used) for example. On top it also indicates what are the ultimate limits for the Java process. When utilization of these 2 sections get high and the capacity is near the maximum available (Eden + From + To + PS Old grow towards MaxHeapSize, and PS Perm grows towards MaxPermSize), chances are you are running out of heap space, one way or another. Referring to this picture might help you understand the output better:
This command will tell you about garbage collections performed and the time spent doing so:
This command will tell you about biggest objects that live in heap:
To investigate further, we might need to refer to the application logs, or use a more sophisticate tools (like YourKit, or Eclipse Memory Analyzer).
4- How much more memory are you using besides heap? Now deduct the RSS figure by your heap capacity, and that's what you are using for everything else.
For me, it was 171MB. If this number is too high, it is worth checking threads. Running too many threads can affect memory usage of the application.
There is no easy way to figure out what's wrong if native memory usage is too high, there are some methods mentioned here though.