Readers,
OutOfMemoryError is not unknown to Java developers. Increasing the heap size almost always gets you past it. Recently I faced the same issue when processing millions of records and increasing heap size (1.3 GB) just got me around it. But it wasn’t a scalable solution as the input number of records could any time grow from few million to many million. Further optimizing the algo (something that drives me) showed the way out. That said, I was curious to find out a way to inspect state of the heap.
There are 2 steps to visualize how the memory is consumed in heap:
1) Specify -XX:+HeapDumpOnOutOfMemoryError VM flag to get the heap dump on first OutOfMemoryError occurence
2) Visualize the dump in Memory Analyzer
Simulation:
Wrote below to reproduce OutOfMemoryError
package com.wordpress.badalchowdhary;
import java.util.ArrayList;
import java.util.List;
public class HeapSpace {
public static void main(String[] args) {
int i = 0;
String msg = "populate heap";
List msgs = new ArrayList();
while (true) {
i++;
// keep adding objects on heap
msgs.add(msg + i);
}
}
}
Before running the program, I specified max heap size to be 10 MB and flag for heap dump.
After running the program, JVM will run out of memory and dump the heap’s state into a .hprof file in project root directory. Below is the snapshot:
The heap dump is ready to be visualized. Memory Analyzer comes very handy. It can be downloaded from here. Below snapshot shows how the heap memory is used up by just adding String objects into the list. You can go to Leak Suspects –> Problem Suspects –> Details.
I think it’s a good way to identify leaks and fat objects that could possibly be tuned.
On tuning terms, I did spend some time to profile the application to visualize time taken by each block. But did not have much luck. If you know of any profiling tools, do leave your comments.
Hopefully can do more than 1 post/month
Your’s Truly!


