問題描述
所以我在這里擁有的是一個 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!