所以我在这里拥有的是一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!