Memory handling
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Naveen_Gupta
Posted On:   Wednesday, June 2, 2004 06:11 AM

I have following program that fills a vector and checks if free memory is less than no. of bytes specified in command line argument to the program. e.g I may want to quit the program when free memory is less than 20000000 (20 MB), for that i get desired result when i run this class as java -Xms100M -Xmx100M MemoryTest 20000000 However, if i run same class with argument as 2000000 (2 MB), I get outof memory error. Can you pl explain how to handle this. Of course, I am delibrately not catching this exception. It seems not working for low values of argument. The program code is: import java.util.*; class MemoryTest    More>>

I have following program that fills a vector and checks if free memory is less than no. of bytes specified in command line argument to the program.


e.g I may want to quit the program when free memory is less than 20000000 (20 MB), for that i get desired result when i run this class as


java -Xms100M -Xmx100M MemoryTest 20000000


However, if i run same class with argument as 2000000 (2 MB), I get outof memory error.


Can you pl explain how to handle this. Of course, I am delibrately not catching this exception.


It seems not working for low values of argument. The program code is:


			
import java.util.*;
class MemoryTest
{
public static void main(String[] args)
{
int i=0;
Runtime rt= Runtime.getRuntime();
Vector v1=new Vector();
long threshold = Integer.parseInt(args[0]);
while(true)
{
v1.addElement("filler");

//After every 200000th time, print free memory
if(i%200000 == 0)
{
System.out.println("Free Memory available: "+(rt.freeMemory()/1000000)+" MB");
}

//if free mem is less than args[0], exit
if(rt.freeMemory() < threshold)
{
System.out.println("Free Memory is less than "+ threshold+" bytes....Exiting the program");
return;
}
i++;
}
}
}
   <<Less

Re: Memory handling

Posted By:   Sean_Owen  
Posted On:   Wednesday, June 2, 2004 06:37 AM

Nothing is wrong, it's just that your test doesn't work exactly how you think.



The line "v1.addElement("filler")" does not allocate any additional memory, most of the time. "filler" is a string constant, so no new memory is allocated for it when you add it to the Vector. And internally, the Vector is just adding the reference to free slots in an internal array.



Once in a while, the Vector has to grow itself though, and when it does, it doubles the amount of storage it uses. That is where you hit the OutOfMemoryError. For low thresholds, the amount of new memory to allocate is probably larger than the threshold, so it jumps straight from enough memory to out of memory.



Do this in the loop for more predictable results: "v1.addElement(new Object())"

About | Sitemap | Contact