简体   繁体   English

删除Java中的一部分数组以释放堆上的内存

[英]Deleting Part of An Array in Java to Free Memory on Heap

I am implementing a dynamic programming algorithm for the knapsack problem in Java. 我正在为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? 我的问题是:如果我在执行操作时从double数组中删除行,Java会在删除时释放内存吗? Or does Java reserve that memory space for the size of the array I originally created? 还是Java会为我最初创建的数组的大小保留该内存空间? If it's the latter, is there a way to manually free the memory in Java? 如果是后者,是否有办法手动释放Java中的内存?

Thanks for your Help! 谢谢你的帮助!

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
}

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. 那将以128 mb的RAM运行您的应用程序。

Yes it works. 是的,它有效。 Java does not have multidimensional arrays but only jagged arrays (arrays of arrays). Java没有多维数组,而只有锯齿状数组(数组的数组)。 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) (有关示例,请参见Sbodd答案)

无法从数组的一部分中释放内存...因为在Java中,您无法从数组中删除元素..相反,您可以横穿该数组并存储到所需大小的另一个数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM