JVM Exception/Error Example: OutOfMemoryError: Java heap space
This is continuing article of out of memory error explanation. In this post I will provide how to reproduce out of memory error.
Target : OutOfMemoryError: Java heap space
I use JVM 1.6 x64 on windows 7 x64 (so, default limit 63MB) , if you use 1.8 x64, it will 1.7Gb+.
Tools :
Target : OutOfMemoryError: Java heap space
I use JVM 1.6 x64 on windows 7 x64 (so, default limit 63MB) , if you use 1.8 x64, it will 1.7Gb+.
Tools :
IDE : Eclipse
Profilers : I have used Visual VM(free) & Yourkit. You may use JConsole(free) also.
I use 2 class, 1 for growing object and another one to run main method & print memory info. You can use single class for that.
public class HeapOOM
{
public void oomByMem() throws Exception
{
int arraySize = 2, loop=1;
TestOOM.showMemoryInfo();
while(true){
System.out.print("\nIteration " + loop++);
TestOOM.showMemoryInfo();
int[] fillupmemory = new int[arraySize];
arraySize*=2;
System.out.println("\nIteration Ends");
Thread.sleep(3000);
}
}
}
public class TestOOM {
public static void main(String[] args) throws Exception
{
new HeapOOM().oomByMem();
}
public static void showMemoryInfo()
{
System.out.print("\nTotal memory : "+Runtime.getRuntime().totalMemory());
System.out.print(" Free : "+Runtime.getRuntime().freeMemory());
System.out.print(" Max : "+Runtime.getRuntime().maxMemory());
}
}
Code summary: It’s very simple, I am allocating integer array and after each loop, I am doubling my allocation and running loop infinite to reach OOM. I am providing thread sleep so that I can get chance to attach profiler.
From yourkit(summary page), the limit shown
At iteration 24 ,I got error shown in eclipse console.
When I profile via your kit, this was the state.
And from Visual VM
The cause : As I was increasing memory allocation doubling each iteration, at the end point , JVM can’t allocate more than default sizing. If you increase heap size from default using –Xmx (I used –Xmx2048m), it will grow more iteration means OOM will be occurring more later on.
Now, you can do some experiment, you can decrease the growth by, not multiplying, by adding 10/50 increment. This will not increase resource allocation in radical way, so garbage collector will get time to collection and you will get long time to create OOM.
Again, if you allocate large number of memory at a time, if it is more than eden space , then you may see OOM also, so better to keep some ration better eden space & old generation(Tenured space).
Link to github.
Thanks.. :)