[英]how to clear objects (HashMap) to be garbage collected - 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). 所以我在这里有一个java程序,它操纵大量数据并将其存储到对象中(主要是哈希映射)。 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 ? 我的问题是丢弃这些数据被垃圾收集的最佳行为是什么?
I have tried the map.clear(), however this is not enough to clear the memory allocated by the map. 我已经尝试过map.clear(),但这还不足以清除地图分配的内存。
EDIT (To add alternatives I have tried) 编辑 (添加我尝试的替代品)
I have also tried the system.gc() to force the garbage collector to run, however it did not help 我也尝试过system.gc()来强制垃圾收集器运行,但它没有帮助
HashMap#clear will throw all entries out of the HashMap, but it will not shrink it back to its initial capacity . HashMap#clear将把所有条目都抛出HashMap,但它不会将其缩小回初始容量 。 That means you will have an empty backing array with (in your case, I guess) space for tens of thousands of entries. 这意味着你将拥有一个空的支持数组(在你的情况下,我猜)空间可以容纳成千上万的条目。
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(具有大致相同数量的数据),只需丢弃整个HashMap实例(将其设置为null
)。
In addition to the above: 除上述内容外:
system.gc()
is not recommended as jvm should be the only one to take care of all the garbage collection. 不推荐使用jvm应该是唯一一个负责所有垃圾收集的人。 Use Class WeakHashMap<K,V>
in this case. 在这种情况下使用Class WeakHashMap<K,V>
。 The objects will automatically be removed if the key is no longer valid 如果密钥不再有效,将自动删除对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.