How to fix the Memory full issue?
Hello,
I am trying to check the available memory before loading a table into memory, but I am getting "Memory full" error the first time I run this code and try to load a table but after running the same code couple of times I am able to allocate memory without "Memory full" error. Can anybody explain this odd behavior and please let me know how I can fix this problem to be able to load the table the very first time I run this code?
long freem = Runtime.getRuntime().freeMemory();
if ( freem < 100000) {
System.out.println("Memory full");
System.out.println("line =" + n + " Free Memory=" + freem);
}
I tried calling Runtime.getRuntime().gc() before checking for the freeMemory; but no luck.
Thank you for your time,
Nish
Hi Nish,
Here's a quick explanation of why you're seeing the behavior you're seeing.
In HotSpot, there's a difference between committed and reserved memory for the heap. Committed memory is the current size of the heap that the GC is managing. Reserved memory is the maximum size the heap can grow to. The defaults, at least on the client system, are something like 4MB committed and 64MB reserved. So, the VM reserves 64MB but only commits and uses 4MB. If the GC decides that the heap is getting full, it will increase the committed space. freeMemory() returns the (estimated!!!) amount of free space in the _committed_ space.
A possible reason for why you saw the more free memory being made available after some allocations is that the GC might have decided to grow the heap, which will have made more free space available than when you launched the VM.
Given the above, any information you might get from freeMemory() is not always reliable, unless you change your heap settings so that the reserved and committed memory is the same (you can do that by using the -Xms and -Xmx parameters).
Maybe checking the free memory explicitly is not a good idea? Can't you just try to allocate the data structure that you need and catch an OutOfMemory exception, which will be thrown if there's really not more free memory in the heap?
Tony (from HS GC Group)