OutOfMemoryError Prevention
Hi all,
I supposed this question has been asked undred times but i can't find an answer.
Is ther one way to prevent OutOfMemoryError. My idea is to test the available free memory using Runtime.freeMemory() and compare if the result is less than one defined constant. But it does'n work. I don't understand the returned result of free memory.
publicstaticvoid main(String[] args){
List<Object> l =new ArrayList<Object>();
System.out.println("init free mem = " + Runtime.getRuntime().freeMemory());
try{
for (int i = 0; i < 1000000000; i++){
l.add(new Object());
}
}catch(Throwable th){
System.out.println("free mem = " + Runtime.getRuntime().freeMemory());
System.out.println("max mem = " + Runtime.getRuntime().maxMemory());
System.out.println("tot mem = " + Runtime.getRuntime().totalMemory());
long used = Runtime.getRuntime().totalMemory() -Runtime.getRuntime().freeMemory();
System.out.println("use mem = " + used);
}
}
This code produces the following output:
init free mem = 1840592
free mem = 5386696
max mem = 66650112
tot mem = 66650112
use mem = 61263416
Why the init free memory is lesser than the free memory when outofmemoryerror ocuurs ?
Thanks
Manu
[2012 byte] By [
Manu38100a] at [2007-10-3 8:06:15]

By default, the VM starts out with a total memory far below 64M and grows it out to 64M as it needs more memory. Try my modifications to your code below and see how max memory grows over time. You can change the default memory settings. Try your original code with -Xms64m and -Xmx64m and you will see the init free is much larger. The -Xms64m tells the vm how much total memory to start with. You can change the max memory with -Xmx128m or even -Xmx5g if you have enough memory.
public static void main(String[] args) {
System.out.println("init memory");
logMemory();
List<Object> l = new ArrayList<Object>();
try {
for (int i = 0; i < 1000000000; i++){
if (i % 10000 == 0) {
System.out.println("At iteration " + i);
logMemory();
}
l.add(new Object());
}
} catch(Throwable th) {
logMemory();
}
}
void logMemory() {
System.out.println("free mem = " + Runtime.getRuntime().freeMemory());
System.out.println("max mem = " + Runtime.getRuntime().maxMemory());
System.out.println("tot mem = " + Runtime.getRuntime().totalMemory());
long used = Runtime.getRuntime().totalMemory() -Runtime.getRuntime().freeMemory();
System.out.println("use mem = " + used);
System.out.println();
}
> Why the init free memory is lesser than the free
> memory when outofmemoryerror occurs ?
After trying a GC and there is not enough availiable free memory then the VM will expand the total memory. What the VM determines as "not enough availiable free memory" is dependent on numerous factors and is dependent on the type of garbage collection you are using. If it can't expand the total memory then it throws a OutOfMemoryError. At the start the VM is able to expand the total memory as needed. Of course this goes on until max memory is reached.