views:

184

answers:

4

I am implementing a dynamic programming algorithm for the knapsack problem in Java. I declare the array and then initialize its size to be [number of objects][capacity of knapsack].

When my number of objects or my capacity gets too large, I get a memory error because I run out of space on the heap. My questions is: If I delete rows from my double array as I go along, will Java free the memory as I delete? Or does Java reserve that memory space for the size of the array I originally created? If it's the latter, is there a way to manually free the memory in Java?

Thanks for your Help!

+1  A: 

It should free the memory a bit later, not necessarily as you remove the rows. It will however reuse that memory for new data.

Probably you're running with to little ram, try increasing it using:

java -Xmx128m you.app.Main

That will run your app with 128 mb of RAM.

OscarRyz
As long as it can reuse the memory for new data i should be ok. I want to be able to add new rows as i delete old rows. Thank you!
kate
+5  A: 

The short answer is "yes" - if you're using arrays like this:

private void foo () {
  int[][] bar = new int[10][10];
  bar[1] = null;  
  //at this point, the array that was in bar[1] is eligible for garbage collection
  //unless someone else has a reference to it
}
Sbodd
But the JVM won't return that that memory to the OS ( at least not in Windows ) but it will keep it for future usage (unless I understand wrong that's what the OP needs isn't ? - mhh maybe not - )
OscarRyz
I've seen the JVM return memory to the OS (Windows XP). It's only when a large percentage of the heap is freed.
Steve Kuo
Thanks! I will try that, and hopefully it will work.
kate
+1  A: 

Yes it works. Java does not have multidimensional arrays but only jagged arrays (arrays of arrays). So the first array is basically only an array of pointers to the real arrays of contents.

That has the positive effect than whenever you assign a new array to one of the jagged areas the old one can be garbage collected. (see Sbodd answer for an example)

Foxfire
Thanks for the explanation.
kate
A: 

it is not possible to free memory from a part of the array...because in java you cannot delete elements from array ..instead of it you can transverse that array and than store into another array of required size....

kanwal1986