如何清除要垃圾收集的对象(HashMap) - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28407307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to clear objects (HashMap) to be garbage collected - Java
提问by Abdelrahman Shoman
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.
所以我在这里拥有的是一个 Java 程序,它处理大量数据并将其存储到对象中(主要是哈希映射)。在运行时间的某个时刻,数据变得无用,我需要丢弃,以便释放一些内存。
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() 强制垃圾收集器运行,但它没有帮助
回答by Thilo
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#clear 会将所有条目从 HashMap 中抛出,但不会将其收缩回其初始容量。这意味着您将有一个空的后备数组(在您的情况下,我猜)有数万个条目的空间。
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:
除上述之外:
- if the entries of the Map are still referenced by some other part of your system, they won't be garbage-collected even when they are removed from the Map (because they are needed elsewhere)
- Garbage collections happens in the background, and only when it is required. So you may not immediately see a lot of memory being freed, and this may not be a problem.
- 如果 Map 的条目仍然被系统的其他部分引用,即使它们从 Map 中删除,它们也不会被垃圾收集(因为它们在其他地方需要)
- 垃圾收集在后台进行,并且仅在需要时进行。所以您可能不会立即看到大量内存被释放,这可能不是问题。
回答by shikjohari
system.gc()
is not recommended as jvm should be the only one to take care of all the garbage collection. Use Class WeakHashMap<K,V>
in this case.
The objects will automatically be removed if the key is no longer valid
不推荐,因为 jvm 应该是唯一一个负责所有垃圾收集的人。Class WeakHashMap<K,V>
在这种情况下使用。如果密钥不再有效,对象将被自动删除