OutOfMemory error can occur due to fragmented heap. This issue is not as common as the heap exhaustion but it is a deadly issue regardless.
What are the symptoms of Heap Fragmentation ?
1. Java.lang.OutOfMemory errors in the Application log file
2. Application is not responsive or extremely slow
3. Unexpected errors in user experience
What causes Heap Fragmentation ?
When JVM allocates memory based on the application demand, the allocated memory needs to be in contiguous blocks. This is by design. As your application runs, GC periodically cleans up unused objects. This leaves ‘holes’ the contiguous blocks of memory. Over time, the heap gets fragmented. The JVM does try its best to ‘compact’ the heap, however it is not a cure-all for a heavily fragmented heap. When the memory demanded by the application is not available as contiguous blocks, OutOfMemory error strikes.
One of the primary reasons heap fragmentation occurs is the demand of ‘large’ memory blocks by the application. This is when you have to get down to the code level troubleshooting working with the Application developer
How to prevent Heap Fragmentation ?
1. Enable verbose Garbage Collection logs and check the log for ‘large’ memory demand. Verbose GC logs should also reveal wealth of other information about
GC cycles such as a)frequency of GC b)duration of GC etc. This should lead you to the fix
2. Review application code with application developer and ensure the memory demanded by the application is not super high
3. Try G1 GC collector. This is the latest GC collector and it is supposed to alleviate fragmentation issues if not altogether avoid it.
Next, you can have all your ducks in the row by writing clean code, optimal ‘max heap’, ‘young generation’ size etc – but this particular Memory issue can still bring you down – Running out of PermGen space.
Previous: Troubleshooting GC: Heap Exhaustion