I have an application that is always growing and growing, the simplified code of my application is
Vector v = new Vector();
publicvoid add_vector (Vector k)
{
v.add(k);
}
publicvoid addingmore (Vector k)
{
for (int i = 0 ; i < 100 ; i++)
add_vector(k);}
}
assume that k is very huge size vector.
As i keep adding this large vector to v therefore i get OutOfMemoryError.
I want to avoid this OutOfMemoryError by actually doing like: say the max memory is 500 then after i add k to v, its used up around 500 then what happen is start deleting one by one the element in v so that the used memory is around 450.
I did this by doing
publicvoid add_vector (Vector k)
{
v.add(k);
long limit = 450;
long used = run.totalMemory() - run.freeMemory();
// assume that totalMemory() value and maxMemory() value
//is 500.
while (used >= limit)
{
v.removeElementAt(0);
System.gc();
used = run.totalMemory() - run.freeMemory();
}
}
but this method is not working as i still getting the out of memory error.i also keep track of the value of run.totalMemory(), run.freeMemory() and (run.totalMemory() - run.freeMemory()) everytime it adding and remove element in v. what happen is its true that the (run.totalMemory() - run.freeMemory()) value is going down as i delete the element from v and calling the System.gc(),but this still doesnt solve the OutOfMemoryError, i keep getting the error eventhough the value is already so small and only 1 element left in v.
I used the System.gc() because if i dont use it after i use v.removeElementAt(0) then the used value is increasing not decreasing.
My goal is to fill the available memory with as many objects added to the vector as possible.
Looks like a you want to cache data as long as your memory supports it and you don't mind if data from cache are removed if memory is needed by other part of progra. The best solution is using SoftReference objects. Please see details of java.lang.ref.SoftReference in Java online Documentation.