問題描述
所以我在這里擁有的是一個 java 程序,它處理大量數(shù)據(jù)并將其存儲到對象中(主要是哈希映射).在運(yùn)行時間的某個時間點,數(shù)據(jù)變得無用,我需要丟棄,以便釋放一些內(nèi)存.
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.
我的問題是丟棄這些數(shù)據(jù)以進(jìn)行垃圾收集的最佳行為是什么?
My question is what would be the best behavior to discard these data to be garbage collected ?
我已經(jīng)嘗試了 map.clear(),但是這不足以清除地圖分配的內(nèi)存.
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() 來強(qiáng)制垃圾收集器運(yùn)行,但是沒有幫助
I have also tried the system.gc() to force the garbage collector to run, however it did not help
推薦答案
HashMap#clear 會將所有條目拋出 HashMap,但 它不會將其縮小到初始容量.這意味著您將有一個空的后備數(shù)組(在您的情況下,我猜)有數(shù)萬個條目的空間.
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.
如果您不打算重復(fù)使用 HashMap(數(shù)據(jù)量大致相同),只需丟棄整個 HashMap 實例(將其設(shè)置為 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 的條目仍被系統(tǒng)的其他部分引用,即使從 Map 中刪除它們也不會被垃圾回收(因為其他地方需要它們)
- 垃圾收集在后臺進(jìn)行,并且僅在需要時進(jìn)行.因此,您可能不會立即看到大量內(nèi)存被釋放,這可能不是問題.
這篇關(guān)于如何清除要被垃圾收集的對象(HashMap) - Java的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!