如何清除要被垃圾收集的对象(HashMap) - Java [英] how to clear objects (HashMap) to be garbage collected - Java

查看:49
本文介绍了如何清除要被垃圾收集的对象(HashMap) - 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).

除上述之外:

  • 如果 Map 的条目仍被系统的其他部分引用,即使从 Map 中删除它们也不会被垃圾回收(因为其他地方需要它们)
  • 垃圾收集在后台进行,并且仅在需要时进行.因此,您可能不会立即看到大量内存被释放,这可能不是问题.

这篇关于如何清除要被垃圾收集的对象(HashMap) - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆