如何清除对象(HashMap)进行垃圾收集 - Java [英] how to clear objects (HashMap) to be garbage collected - Java
问题描述
所以我在这里有一个java程序,它操纵大量数据并将其存储到对象中(主要是哈希映射)。在运行时间的某个时刻,数据变得无用,我需要丢弃,这样我就可以释放一些内存。
So what I am having here is a java program the manipulates a huge amount of data and store it into objects (Mainly hash-maps). At some point of the running time the data becomes useless and I need to discard so I can free up some memory.
我的问题是丢弃的最佳行为是什么这些数据是垃圾收集的?
My question is what would be the best behavior to discard these data to be garbage collected ?
我已经尝试过map.clear(),但是这还不足以清除地图分配的内存。
I have tried the map.clear(), however this is not enough to clear the memory allocated by the map.
编辑(添加我尝试过的替代品)
EDIT (To add alternatives I have tried)
我也尝试过system.gc()强制垃圾收集器运行,但它没有帮助
I have also tried the system.gc() to force the garbage collector to run, however it did not help
推荐答案
HashMap #clear将全部抛出来自HashMap的条目,但它不会缩小到最初容量。这意味着你将有一个空的后备数组(在你的情况下,我猜)空间可以容纳成千上万的条目。
HashMap#clear will throw all entries out of the HashMap, but it will not shrink it back to its initial capacity. That means you will have an empty backing array with (in your case, I guess) space for tens of thousands of entries.
如果你不打算重复使用HashMap(具有大致相同数量的数据),只需丢弃整个HashMap实例(将其设置为 null
)。
If you do not intend to re-use the HashMap (with roughly the same amount of data), just throw away the whole HashMap instance (set it to null
).
除上述内容外:
- 如果地图的条目仍被系统的其他部分引用,则即使从地图中删除它们也不会被垃圾收集(因为它们需要在其他地方使用)。
- 垃圾收集在后台发生,并且仅在需要时才发生。因此,您可能不会立即看到大量内存被释放,这可能不是问题。
这篇关于如何清除对象(HashMap)进行垃圾收集 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!